共計 393 個字符,預計需要花費 1 分鐘才能閱讀完成。
在 Python 中,可以使用 strip() 方法來刪除字符串兩邊的空白字符。
示例代碼:
string = " Hello, World!
"
new_string = string.strip()
print(new_string)
輸出結果:
Hello, World!
strip() 方法將刪除字符串兩邊的空白字符,包括空格、制表符和換行符。如果只想刪除右邊的空白字符,可以使用 rstrip() 方法。
示例代碼:
string = " Hello, World!
"
new_string = string.rstrip()
print(new_string)
輸出結果:
Hello, World!
注意,strip() 和 rstrip() 方法返回的是刪除空白字符后的新字符串,并不會修改原來的字符串。如果想修改原來的字符串,可以將新字符串賦值回原來的變量。
丸趣 TV 網 – 提供最優質的資源集合!
正文完