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}'")
输出结果为:
string: ' \n shark\n squid\t '
remove leading: 'shark\n squid\t '
remove trailing: ' \n shark\n squid'
remove both: 'shark\n squid'
输出显示,如果省略chars
参数并使用strip
方法,则只会从字符串中去除前导和尾部的空格、换行符和制表符。任何不在字符串开头或结尾的空白字符都不会被去除。
使用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}'")
输出为:
string: '\n sammy\n shark\t '
remove only leading newline: ' sammy\n shark\t '
输出结果表明,lstrip()
方法能够删除字符串开头的换行符,但不能删除开头的空格。
请注意,strip
方法只会在特定字符位于字符串的首尾位置时才进行删除。例如,你无法使用rstrip()
来仅删除s3 = '\n sammy\n shark\t '
中末尾的制表符,因为制表符后面还有空格。
结论
在本文中,你使用了strip()
、rstrip()
和lstrip()
方法来从字符串中去除前导和尾随的空白字符。若要学习如何从字符串中删除所有空格和特定字符,请参考《如何在Python中删除字符串中的空格》。继续学习更多的Python字符串教程。