Python 中去除字符串首尾空格可以使用 strip() 函数。该函数可以删除字符串开头和结尾的所有空格、制表符、换行符等空白字符。

示例代码如下:

s = '  hello world  '
s = s.strip()
print(s) # 输出 'hello world'

还可以利用 lstrip()rstrip() 函数分别删除字符串左侧和右侧的空格。

示例代码如下:

s = '  hello world  '
s = s.lstrip() # 删除左侧空格
print(s) # 输出 'hello world  '

s = '  hello world  '
s = s.rstrip() # 删除右侧空格
print(s) # 输出 '  hello world'
Python 字符串去除首尾空格: strip(), lstrip(), rstrip() 函数详解

原文地址: https://www.cveoy.top/t/topic/okyC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录