溫馨提示×

python strip函數怎么使用

小億
140
2023-09-26 01:12:39
欄目: 編程語言

strip函數可以用來移除字符串的頭尾指定字符,默認移除字符串兩端的空格或換行符。

基本用法:

string.strip([chars])

其中,string表示要操作的字符串,chars表示要移除的字符集合。如果不指定chars參數,默認移除字符串兩端的空格或換行符。

示例:

string = "   hello world   "
new_string = string.strip()
print(new_string)  # 輸出:hello world

如果要移除字符串中指定的字符,可以通過傳入chars參數來實現。

示例:

string = "hello world"
new_string = string.strip("hld")
print(new_string)  # 輸出:ello wor

在上面的示例中,strip函數移除了字符串"hello world"中的字符"h","l""d"。

另外,還有lstrip函數和rstrip函數分別用于移除字符串左側和右側的指定字符。用法與strip函數類似。

更多用法可以參考Python官方文檔:https://docs.python.org/3/library/stdtypes.html#str.strip

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女