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()

同上

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章