有没有一个Python函数可以从字符串中删除空格(空格和制表符)?
所以给定的输入" \t example string\t "
变成"example string"
.
对于两侧的空白,请使用str.strip https://docs.python.org/3/library/stdtypes.html#str.strip:
s = " \t a string example\t "
s = s.strip()
对于右侧的空白,请使用str.rstrip https://docs.python.org/3/library/stdtypes.html#str.rstrip:
s = s.rstrip()
对于左侧的空白,请使用str.lstrip https://docs.python.org/3/library/stdtypes.html#str.lstrip:
s = s.lstrip()
您可以提供一个参数来将任意字符剥离给任何这些函数,如下所示:
s = s.strip(' \t\n\r')
这将剥夺任何空间,\t
, \n
, or \r
字符串两侧的字符。
上面的示例仅删除字符串左侧和右侧的字符串。如果您还想删除字符串中间的字符,请尝试re.sub https://docs.python.org/3/library/re.html#re.sub:
import re
print(re.sub('[\s+]', '', s))
应该打印出:
astringexample
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)