字符串
1、基本的字符串操作
所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串同样适用。但请牢记,字符串不可改变,因此类似一下分片赋值是不合法的。
>>> aaa[2:]='ad'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
2、字符串方法
(1) find方法可以在较长字符串中查找子字符串。它返回子串所在位置的最左端索引,如果没有找到则返回-1
>>> a='adfadf'
>>> a.find(a)
0
>>> a.find('a')
0
>>> a.find(j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined
>>> a.find('j')
-1
>>> a.find('ad')
0
>>> a.find('ad',1) #只提供了起始点
3
>>> a.find('ad',1,3) #提供了起始点和结束点
-1
注意,范围包括第一个索引,但不包括第二个索引。
(2) join是split方法的逆方法,用来在队列中添加元素
(3) lower方法返回字符串的小写字母版。
>>> name='ZDU'
>>> 'zdu' in name
False
>>> 'zdu' in name.lower()
True
(4) replace方法返回某字符串的所有匹配项均被替换之后得到的字符串。
>>> "this is a
test".replace('is','at')
'that at a test'
(5) split方法,是join的逆用法,用来将字符串分割成序列。
>>> 'this is a test'.split()
['this', 'is', 'a', 'test']
>>> '1+2+3+4'.split('+')
['1', '2', '3', '4']
>>> '1+2+3+4'.split(+)
File "<stdin>", line 1
'1+2+3+4'.split(+)
^
SyntaxError: invalid syntax
(6) strip方法返回去除两侧(不包括内部)空格的字符串。
>>> name=' zd u '
>>> name.strip()
'zd u'
>>> name
' zd u '
>>> name='@@adfa@adf@'
>>> name.strip('@')
'adfa@adf'
可以看到假如有参数的话,则会删除两侧的参数
(7) translate和replace方法一样,可以替换字符串中的某些部分,但是和前者不同的是,translate方法只处理单个字符。它的优势在于可以同时进行多个替换,有时候比replace效率高