Python 字符串 strip() 方法

實例

刪除字符串開頭和結尾的空格:

txt = "     banana     "
x = txt.strip()
print("of all fruits", x, "is my favorite")

運行實例

定義和用法

strip() 方法刪除任何前導(開頭的空格)和尾隨(結尾的空格)字符(空格是要刪除的默認前導字符)。

語法

string.strip(characters)

參數值

參數 描述
characters 可選。一組字符,要刪除的前導/尾隨字符的字符。

更多實例

實例

刪除前導和尾隨字符:

txt = ",,,,,rrttgg.....banana....rrr"
x = txt.strip(",.grt")
print(x)

運行實例