共計 355 個字符,預計需要花費 1 分鐘才能閱讀完成。
可以使用 strip() 方法來去除字符串首尾的空格。
示例代碼如下:
string = "hello world"
new_string = string.strip()
print(new_string) # 輸出結果為 "hello world"
strip() 方法可以去除字符串首尾的空格,并返回一個新的字符串。如果想去除字符串中間的空格,可以使用 replace() 方法將空格替換為空字符串,示例如下:
string = "hello world"
new_string = string.replace("","")
print(new_string) # 輸出結果為 "helloworld"
另外,如果只想去除字符串開頭的空格,可以使用 lstrip() 方法;如果只想去除字符串末尾的空格,可以使用 rstrip() 方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完