小编典典

Python-如何修剪空白?

python

是否有Python函数可以从字符串中修剪空格(空格和制表符)?

例如:\t example string\t→example string


阅读 750

收藏
2020-02-23

共1个答案

小编典典

两侧的空格:

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 re
print re.sub('[\s+]', '', s)

那应该打印出来:

astringexample
2020-02-23