一、字符串的拼接 .join()
1.对序列操作:将多个字符串拼接为一个字符串,只作用于两两元素之间
>>> s=['1','23',' ','56','_','ab','de']
>>> ','.join(s)
'1,23, ,56,_,ab,de'
>>> ':'.join(s)
'1:23: :56:_:ab:de'
相当于:
s=['1','23',' ','56','_','ab','de']
temp=''
for i in s:
temp=temp+i+','
ss=temp.strip(',')
##结果如下:
>>> ss
'1,23, ,56,_,ab,de'
2.对字符串操作:将一个字符串里的多个元素间插入同一符号
>>> s='123456ab*'
>>> '; '.join(s)
'1; 2; 3; 4; 5; 6; a; b; *'
除此之外,join()还可以对元组、字典进行操作。
二、字符串的替换与查找 replace、find
1.替换replace
>>> temp
'1,23, ,56,_,ab,de,'
>>> temp.replace('2','re')
'1,re3, ,56,_,ab,de,'
>>> temp.replace('23, ,','re')
'1,re56,_,ab,de,'
#默认替换所有
>>> temp.replace(',',':')
'1:23: :56:_:ab:de:'
#可以限定替换前几个
>>> temp.replace(',',':',2)
'1:23: ,56,_,ab,de,'
2.查找find
格式:str.find(str,beg=0,end=len(string)),举例如下:
>>> temp
'1,23, ,56,_,ab,de,'
#返回第一个所要查找的元素的下标
>>> temp.find('1')
0
>>> temp.find('1,23, ,56,_,ab,de,')
0
>>> temp.find(',')
1
>>> temp.find('23')
2
#没有查找到的元素返回-1
>>> temp.find(':')
-1
#可以限定查找的范围
>>> temp.find(',',2,5)
4
#可以倒序查找
>>> temp.rfind(',')
17
>>> temp.rfind('de')
15