1. 使用 `strip()` 方法:
my_string = " Hello World! "
stripped_string = my_string.strip()
print(stripped_string) 输出:"Hello World!"
2. 使用 `lstrip()` 方法去除左侧空格:
my_string = " Hello World! "
stripped_string = my_string.lstrip()
print(stripped_string) 输出:"Hello World! "
3. 使用 `rstrip()` 方法去除右侧空格:
my_string = " Hello World! "
stripped_string = my_string.rstrip()
print(stripped_string) 输出:" Hello World!"
4. 使用正则表达式 `re.sub()` 函数:
import re
my_string = " Hello World! "
stripped_string = re.sub(r"^\s+|\s+$", "", my_string)
print(stripped_string) 输出:"Hello World!"
5. 使用循环手动遍历字符串删除首尾空格:
my_string = " Hello World! "
new_string = ""
for char in my_string:
if char != " ":
new_string += char
break
for i in range(len(my_string) - 1, -1, -1):
if my_string[i] != " ":
new_string += my_string[i]
break
print(new_string) 输出:"Hello World!"
选择哪种方法取决于您的具体需求。`strip()` 方法是最简单快捷的,而正则表达式提供了更灵活的匹配模式