我如何修剪空白?是否有一个Python函数可以从字符串中修剪空格(空格和制表符)?示例:\t example string\t→example string
3 回答

鸿蒙传说
TA贡献1865条经验 获得超7个赞
双方空白:
s = " \t a string example\t "s = s.strip()
右侧的空白:
s = s.rstrip()
左侧的空白:
s = s.lstrip()
正如thedz指出的那样,你可以提供一个参数来将任意字符剥离到这些函数中,如下所示:
s = s.strip(' \t\n\r')
这将去除任何空间,\t
,\n
,或\r
从左侧字符,右手侧,或该字符串的两侧。
上面的示例仅从字符串的左侧和右侧删除字符串。如果您还要从字符串中间删除字符,请尝试re.sub
:
import reprint re.sub('[\s+]', '', s)
那应该打印出来:
astringexample

临摹微笑
TA贡献1982条经验 获得超2个赞
trim调用Python 方法strip:
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim

尚方宝剑之说
TA贡献1788条经验 获得超4个赞
对于前导和尾随空格:
s = ' foo \t 'print s.strip() # prints "foo"
否则,正则表达式起作用:
import re pat = re.compile(r'\s+')s = ' \t foo \t bar \t 'print pat.sub('', s) # prints "foobar"
添加回答
举报
0/150
提交
取消