示例 1:使用 strip()
my_string = " Python "
print(my_string.strip())
输出
Python
strip()
从字符串中删除开头和结尾的字符,包括空格。
但是,如果字符串中有像 '\n'
这样的字符,并且您只想删除空格,则需要像以下代码所示在 strip()
方法上明确指定它。
my_string = " \nPython "
print(my_string.strip(" "))
输出
Python
要了解更多信息,请访问 Python 字符串 strip()。
示例 2:使用正则表达式
import re
my_string = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)
print(output)
输出
Hello python
在正则表达式中,\s
表示空格,\
是或运算。+
表示其左侧模式出现一次或多次。
在 Python 正则表达式 了解更多关于正则表达式的信息。
另请阅读