字符串也是一種序列,因此,通用的序列操作,比如索引,分片,加法,乘法等對它同樣適用。比如:
>>> s = 'hello, '
>>> s[0] # 索引
'h'
>>> s[1:3] # 分片
'el'
>>> s + 'world' # 加法
'hello, world'
>>> s * 2 # 乘法
'hello, hello, '
但需要注意的是,字符串和元組一樣,也是不可變的,所以你不能對它進(jìn)行賦值等操作:
>>> s = 'hello'
>>> s[1] = 'ab' # 不能對它進(jìn)行賦值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
除了通用的序列操作,字符串還有自己的方法,比如 join, lower, upper 等。字符串的方法特別多,這里只介紹一些常用的方法,如下:
find 方法用于在一個(gè)字符串中查找子串,它返回子串所在位置的最左端索引,如果沒有找到,則返回 -1。
看看例子:
>>> motto = "to be or not to be, that is a question"
>>> motto.find('be') # 返回 'b' 所在的位置,即 3
3
>>> motto.find('be', 4) # 指定從起始位置開始找,找到的是第 2 個(gè) 'be'
16
>>> motto.find('be', 4, 7) # 指定起始位置和終點(diǎn)位置,沒有找到,返回 -1
-1
split 方法用于將字符串分割成序列。
看看例子:
>>> '/user/bin/ssh'.split('/') # 使用 '/' 作為分隔符
['', 'user', 'bin', 'ssh']
>>> '1+2+3+4+5'.split('+') # 使用 '+' 作為分隔符
['1', '2', '3', '4', '5']
>>> 'that is a question'.split() # 沒有提供分割符,默認(rèn)使用所有空格作為分隔符
['that', 'is', 'a', 'question']
需要注意的是,如果不提供分隔符,則默認(rèn)會使用所有空格作為分隔符(空格、制表符、換行等)。
join 方法可以說是 split 的逆方法,它用于將序列中的元素連接起來。
看看例子:
>>> '/'.join(['', 'user', 'bin', 'ssh'])
'/user/bin/ssh'
>>>
>>> '+'.join(['1', '2', '3', '4', '5'])
'1+2+3+4+5'
>>> ' '.join(['that', 'is', 'a', 'question'])
'that is a question'
>>> ''.join(['h', 'e', 'll', 'o'])
'hello'
>>> '+'.join([1, 2, 3, 4, 5]) # 不能是數(shù)字
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
strip 方法用于移除字符串左右兩側(cè)的空格,但不包括內(nèi)部,當(dāng)然也可以指定需要移除的字符串。
看看例子:
>>> ' hello world! '.strip() # 移除左右兩側(cè)空格
'hello world!'
>>> '%%% hello world!!! ####'.strip('%#') # 移除左右兩側(cè)的 '%' 或 '#'
' hello world!!! '
>>> '%%% hello world!!! ####'.strip('%# ') # 移除左右兩側(cè)的 '%' 或 '#' 或空格
'hello world!!!'
replace 方法用于替換字符串中的所有匹配項(xiàng)。
看看例子:
>>> motto = 'To be or not To be, that is a question'
>>> motto.replace('To', 'to') # 用 'to' 替換所有的 'To',返回了一個(gè)新的字符串
'to be or not to be, that is a question'
>>> motto # 原字符串保持不變
'To be or not To be, that is a question'
translate 方法和 replace 方法類似,也可以用于替換字符串中的某些部分,但 translate 方法只處理單個(gè)字符。
translate 方法的使用形式如下:
str.translate(table[, deletechars]);
其中,table 是一個(gè)包含 256 個(gè)字符的轉(zhuǎn)換表,可通過 maketrans 方法轉(zhuǎn)換而來,deletechars 是字符串中要過濾的字符集。
看看例子:
>>> from string import maketrans
>>> table = maketrans('aeiou', '12345')
>>> motto = 'to be or not to be, that is a question'
>>> motto.translate(table)
't4 b2 4r n4t t4 b2, th1t 3s 1 q52st34n'
>>> motto
'to be or not to be, that is a question'
>>> motto.translate(table, 'rqu') # 移除所有的 'r', 'q', 'u'
't4 b2 4 n4t t4 b2, th1t 3s 1 2st34n'
可以看到,maketrans 接收兩個(gè)參數(shù):兩個(gè)等長的字符串,表示第一個(gè)字符串的每個(gè)字符用第二個(gè)字符串對應(yīng)位置的字符替代,在上面的例子中,就是 'a' 用 '1' 替代,'e' 用 '2' 替代,等等,注意,是單個(gè)字符的代替,而不是整個(gè)字符串的替代。因此,motto 中的 o 都被替換為 4,e 都被替換為 2,等等。
lower/upper 用于返回字符串的大寫或小寫形式。
看看例子:
>>> x = 'PYTHON'
>>> x.lower()
'python'
>>> x
'PYTHON'
>>>
>>> y = 'python'
>>> y.upper()
'PYTHON'
>>> y
'python'