介紹
在Python中,經常會遇到需要將字元串中的空格去除的情況,因為空格會影響字元串的比較和顯示。本文將介紹如何用Python去除字元串中的空格,以及如何處理空格、製表符和換行符。
正文
一、python去除空格
在Python中,可以使用strip()函數去除字元串開頭和結尾的空格。strip()函數返回的是去除空格後的新字元串,原字元串不會被修改,示例如下:
str = " hello world " new_str = str.strip() print(new_str) # "hello world"
可以看到,strip()函數去除了字元串開頭和結尾的空格。
除了strip()函數,Python還提供了lstrip()函數和rstrip()函數用於去除字元串左邊和右邊的空格。示例如下:
str = " hello world " new_str1 = str.lstrip() new_str2 = str.rstrip() print(new_str1) # "hello world " print(new_str2) # " hello world"
二、python去除空格空行
除了去除字元串中的空格,有時還需要去除字元串中的空行。下面是如何使用Python去除空行的示例:
str = "hello\n\nworld\n" new_str = str.replace("\n","") print(new_str) # "helloworld"
可以看到,使用replace()函數將字元串中的空行替換為空即可。
三、python輸出空格怎麼去除
在Python中,使用print()函數輸出字元串時,會默認在字元串末尾添加一個換行符。如果想要去除字元串末尾的換行符,可以使用rstrip()函數。示例如下:
str = "hello world\n" print(str.rstrip()) # "hello world"
代碼示例
下面是對上述內容的代碼示例:
# 去除字元串開頭和結尾的空格 str = " hello world " new_str = str.strip() print(new_str) # 去除字元串左邊和右邊的空格 str = " hello world " new_str1 = str.lstrip() new_str2 = str.rstrip() print(new_str1) print(new_str2) # 去除字元串中的空行 str = "hello\n\nworld\n" new_str = str.replace("\n","") print(new_str) # 去除字元串末尾的換行符 str = "hello world\n" print(str.rstrip())
總結
本文介紹了如何用Python去除字元串中的空格、空行和字元串末尾的換行符。希望本文能夠對Python初學者們有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154192.html