简介
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}'")
输出为:
Outputstring: '
shark
squid '
remove leading: 'shark
squid '
remove trailing: '
shark
squid'
remove both: 'shark
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}'")
输出为:
Outputstring: '
sammy
shark '
remove only leading newline: ' sammy
shark '
输出显示lstrip()
方法可以删除开头的换行符,但不能删除字符串开头的空格。
请注意,strip方法只会在它们是最外层的开头和结尾字符时才删除特定字符。例如,你不能使用rstrip()
方法仅删除s3 = '\n sammy\n shark\t '
中\t
后面的制表符,因为后面有空格。
结论
在本文中,你使用了strip()
、rstrip()
和lstrip()
方法来删除字符串开头和结尾的空白字符。若想了解如何从字符串中删除空格和字符,请参考如何在Python中从字符串中删除空格。继续学习更多Python字符串教程。
Source:
https://www.digitalocean.com/community/tutorials/python-trim-string-rstrip-lstrip-strip