python--字符串的常用方法总结

1. 去掉字符串的开头、结尾、中间的不需要字符

1.1 strip()

strip()方法可用来从字符串的开头和结尾处丢弃掉指定字符,默认是空格符,也可以自定其他字符

>>>'hello   '.strip()
'hello'
>>>'-----hellop======'.strip('-=')
'hello'

1.2 lstrip()

只能从左边删除指定字符

>>>'  python  '.lstrip()
'python  '
>>>'    __+===python'.lstrip(' _=+')
'python'

1.3 rstrip()

同上,只不过是从右边开始

2. 对齐字符串

2.1 ljust()

左对齐,接收至多两个参数,第一个参数表示长度,第二个为填充字符,长度不够,默认以空格符填充,也可以指定其他字符

>>>'hello'.ljust(10)
'hello     '
>>>'hello'.ljust(10, '*')
'hello*****'

2.2 rjust()

同ljust()

2.3 center()

>>>'hello'.center(10)
'  hello   '
>>>'hello'.center(10, '=')
'==hello==='

3.字符串拼接

3.1 join()

>>>' '.join(['name', 'age', 'address'])
'name age address' 

4.查找子字符串的位置

4.1 index()

index() 方法检测字符串中是否包含子字符串 ,如果指定 begin 和 end 范围,则检查是否包含在指定范围内,如果存在就返回第一个配置到位置, 该方法与 find()方法一样,只不过如果str不在 string中会报一个ValueError异常,而find()会返回-1表示查找失败。

>>>'abcabc'.index('a')
0
>>>'abcabc'.index('a', 2)
3
>>>'abcabc'.index('av')
Traceback (most recent call last):
  File "/usr/lib/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
ValueError: substring not found

4.2 find()

同上

4.4 rfind()

同上

猜你喜欢

转载自blog.csdn.net/weixin_42237702/article/details/103753638