共計 508 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
Python 中的 strip() 函數(shù)是用來刪除字符串中的指定字符,默認情況下是刪除字符串兩端的空格或換行符。
可以使用以下語法來使用 strip() 函數(shù):
string.strip([chars])
其中,string 表示要操作的字符串,[chars] 是可選參數(shù),用來指定要刪除的字符。如果不指定 chars,則默認刪除字符串兩端的空格或換行符。
以下是一些使用 strip() 函數(shù)的示例:
示例 1:刪除字符串兩端的空格
string = "hello world"
new_string = string.strip()
print(new_string) # 輸出: "hello world"
示例 2:刪除字符串兩端的特定字符
string = ">>>hello world<<<")
print(new_string) # 輸出: "hello world"
示例 3:刪除字符串兩端的換行符
string = "\nhello world\n"
new_string = string.strip("\n")
print(new_string) # 輸出: "hello world"
需要注意的是,strip() 函數(shù)不會修改原始字符串,而是返回一個新的字符串。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完