Python字符串去除空格:strip()、lstrip() 和 rstrip() 方法详解
在 Python 中,可以使用字符串的 'strip()' 方法来去除字符串前后的空格。例如:
s = ' hello world'
s = s.strip()
print(s) # 输出 'hello world'
如果只想去除字符串前面的空格,可以使用 'lstrip()' 方法:
s = ' hello world'
s = s.lstrip()
print(s) # 输出 'hello world '
如果只想去除字符串后面的空格,可以使用 'rstrip()' 方法:
s = ' hello world '
s = s.rstrip()
print(s) # 输出 ' hello world'
注意,这些方法返回的是一个新的字符串,原始字符串不会被修改。如果要修改原始字符串,需要将返回值重新赋值给原始变量。
原文地址: https://www.cveoy.top/t/topic/l0kK 著作权归作者所有。请勿转载和采集!