欢迎访问宙启技术站
智能推送

Python字符串去除空格:使用strip()、lstrip()和rstrip()函数去除字符串两端的空格

发布时间:2024-01-11 03:35:58

在Python中,我们可以使用strip()函数去除字符串两端的空格。该函数返回一个去除空格的新字符串,不会修改原始字符串。

string = "   Hello, World!   "
new_string = string.strip()
print(new_string)  # 输出:"Hello, World!"

除了strip()函数,Python还提供了lstrip()和rstrip()函数,分别用于去除字符串左端和右端的空格。

string = "   Hello, World!   "
new_string = string.lstrip()
print(new_string)  # 输出:"Hello, World!   "

string = "   Hello, World!   "
new_string = string.rstrip()
print(new_string)  # 输出:"   Hello, World!"

strip()、lstrip()和rstrip()函数也可以接受一个参数,用于指定要去除的字符。比如,如果我们想去除字符串两端的"!"字符,可以这样写:

string = "!!Hello, World!!"
new_string = string.strip("!")
print(new_string)  # 输出:"Hello, World"

需要注意的是,strip()、lstrip()和rstrip()函数只会去除字符串两端的空格或指定字符,不会去除字符串内部的空格。如果要去除字符串内部的空格,可以使用replace()函数或正则表达式。

string = "Hello,   World!"
new_string = string.replace(" ", "")
print(new_string)  # 输出:"Hello,World!"

import re
string = "Hello,   World!"
new_string = re.sub("\s+", "", string)
print(new_string)  # 输出:"Hello,World!"

以上是使用strip()、lstrip()和rstrip()函数去除字符串两端空格的例子。通过使用这些函数,我们可以方便地处理字符串中的空格问题。