Python中strip() 方法用於移除字串頭尾指定的字元(預設為空格或換行符)或字元序列。
注意:此方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符。
它的函數原型:string.strip(s[, chars]),它傳回的是字串的副本,並刪除前導和後綴字元。
(意思就是你想去掉字串裡面的哪些字符,那麼你就把這些字符當參數傳入。此函數只會刪除頭和尾的字符,中間的不會刪除。)
如果strip()的參數為空,那麼會預設刪除字串頭和尾的空白字元(包括\n,\r,\t這些)。
lstrip():移除左邊
rstrip():移除右邊

#範例一:
1 2 3 4 5 6 7 8 9 | >>> str = ' ab cd '
>>> str
' ab cd '
>>> str.strip() #删除头尾空格
'ab cd'
>>> str.lstrip() #删除开头空格
'ab cd '
>>> str.rstrip() #删除结尾空格
' ab cd'
|
登入後複製
相關推薦:《 Python影片教學》
範例二:
1 2 3 4 5 6 7 | >>> str2 = '1a2b12c21'
>>> str2.strip('12') #删除头尾的1和2
'a2b12c'
>>> str2.lstrip('12') #删除开头的1和2
'a2b12c21'
>>> str2.rstrip('12') #删除结尾的1和2
'1a2b12c'
|
登入後複製
範例三:
1 2 3 4 5 6 7 | a= "aabcacb1111acbba"
print (a.strip( "abc" ))
print (a.strip( "acb" ))
print (a.strip( "bac" ))
print (a.strip( "bca" ))
print (a.strip( "cab" ))
print (a.strip( "cba" ))
|
登入後複製
輸出:
以上是python中的strip是什麼意思的詳細內容。更多資訊請關注PHP中文網其他相關文章!