内容正文:
Python中
字符串的处理
林城中学 陈 洁
重逢旧友
字符串,不可变序列,不支持直接修改。
>>> t =‘good’
>>> t[0] =‘G’
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
t[0]='G'
TypeError: 'str' object does not support item assignment
引号 ‘ ’或“ ”
str
字符串的操作
1、空字符串和len()函数
>>> c =“” #c为空字符串
>>> len(c)
>>> s =“中国浙江湖州”
>>> len(s)
>>> s =“中国浙江湖州ABCDE” #中文与英文字符都算一个字符
0
6
11
导引P17:1(1)
字符串的操作
2、字符串拼接
>>> a =‘hello ’+’world!’
>>> a
>>> “33”+”44”
>>> “33”+44
‘hello world!’
‘3344’
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
“33”+44
TypeError: can only concatenate str (not "int") to str
字符串的操作
3、查找字符与统计
>>> s =“apple,peach,banana,peach,pear”
>>> s.find(“peach”) #从左开始查找
>>> s.rfind(“p”) #从右开始查找
>>> s.rfind(“wo”) #找不到返回-1
>>> s.count(“pea”) #统计次数
6
25
-1
3
导引P17:1(2)
字符串的操作
4、分割与合并字符
>>> a =“to be or not to be”
>>> a.split( ) #默认分隔符是空格,结果是列表
>>> a.split(‘be’