如何在Python中删除字符串中的空白

介紹

Python 提供了三種方法,您可以使用這些方法來修剪字符串並返回新的字符串對象。字符串修剪方法可以修剪前置空格、尾隨空格,或兩者兼而有之。要了解更多有關刪除空格的信息,包括如何刪除所有空格或僅刪除重復空格,請參閱如何在Python中從字符串中刪除空格

空格包括所有Unicode空格字符,如空格、制表符(\t)、回車符(\r)和換行符(\n)。Python str() 類有以下方法,您可以使用這些方法來修剪字符串中的空格:

  • strip([chars]):修剪字符串的兩端的字符。當省略 chars 或為 None 時,返回一個新字符串,其中移除了所有前置和尾隨空格。
  • rstrip([chars]):修剪字符串的右側的字符。當省略 chars 或為 None 時,返回一個新字符串,其中移除了所有尾隨空格。
  • lstrip([chars]):修剪字符串的左側的字符。當省略 chars 或為 None 時,返回一個新字符串,其中移除了所有前置空格。

使用Strip方法从字符串中删除空白

以下示例演示如何从字符串中修剪前导空格、尾随空格以及前导和尾随空格:

s1 = '  shark  '
print(f"string: '{s1}'")

s1_remove_leading = s1.lstrip()
print(f"remove leading: '{s1_remove_leading}'")

s1_remove_trailing = s1.rstrip()
print(f"remove trailing: '{s1_remove_trailing}'")

s1_remove_both = s1.strip()
print(f"remove both: '{s1_remove_both}'")

输出为:

string: '  shark  '
remove leading: 'shark  '
remove trailing: '  shark'
remove both: 'shark'

以下示例演示如何使用相同的strip方法从字符串中修剪多个空白字符:

s2 = '  \n shark\n squid\t  '
print(f"string: '{s2}'")

s2_remove_leading = s2.lstrip()
print(f"remove leading: '{s2_remove_leading}'")

s2_remove_trailing = s2.rstrip()
print(f"remove trailing: '{s2_remove_trailing}'")

s2_remove_both = s2.strip()
print(f"remove both: '{s2_remove_both}'")

输出为:

Output
string: ' shark squid ' remove leading: 'shark squid ' remove trailing: ' shark squid' remove both: 'shark squid'

输出显示,使用strip方法并省略chars参数仅从字符串的开头和结尾移除空格、换行和制表符。不在字符串开头或结尾的任何空白都不会被移除。

使用Strip方法从字符串中删除特定的空白字符

您还可以通过指定chars参数,仅从字符串开头和结尾删除特定字符或字符。以下示例演示如何仅修剪字符串开头的换行符:

s3 = '\n  sammy\n  shark\t  '
print(f"string: '{s3}'")

s3_remove_leading_newline = s3.lstrip('\n')
print(f"remove only leading newline: '{s3_remove_leading_newline}'")

输出为:

Output
string: ' sammy shark ' remove only leading newline: ' sammy shark '

輸出顯示lstrip()方法會移除字串的前置換行符號,但不會移除字串中的前置空格。

請注意,strip方法僅在它們是最外層的前置和尾隨字符時才移除特定字符。例如,您無法使用rstrip()s3 = '\n sammy\n shark\t '僅移除尾隨的tab字符,因為在\t後面有空格。

結論

在本文中,您使用了strip()rstrip()lstrip()方法來修剪字串的前置和尾隨空格。要了解如何從字串中移除空格和字符,請參閱如何在Python中從字串中移除空格。繼續通過更多Python字串教程學習。

Source:
https://www.digitalocean.com/community/tutorials/python-trim-string-rstrip-lstrip-strip