共計(jì) 523 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
strip 函數(shù)可以用來移除字符串的頭尾指定字符,默認(rèn)移除字符串兩端的空格或換行符。
基本用法:
string.strip([chars])
其中,string
表示要操作的字符串,chars
表示要移除的字符集合。如果不指定 chars
參數(shù),默認(rèn)移除字符串兩端的空格或換行符。
示例:
string = "hello world"
new_string = string.strip()
print(new_string) # 輸出:hello world
如果要移除字符串中指定的字符,可以通過傳入 chars
參數(shù)來實(shí)現(xiàn)。
示例:
string = "hello world"
new_string = string.strip("hld")
print(new_string) # 輸出:ello wor
在上面的示例中,strip
函數(shù)移除了字符串 "hello world"
中的字符 "h"
,"l"
和"d"
。
另外,還有 lstrip
函數(shù)和 rstrip
函數(shù)分別用于移除字符串左側(cè)和右側(cè)的指定字符。用法與 strip
函數(shù)類似。
更多用法可以參考 Python 官方文檔:https://docs.python.org/3/library/stdtypes.html#str.strip</p>
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完