我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
当前回答
最简单的是使用replace:
"foo bar\t".replace(" ", "").replace("\t", "")
或者,使用正则表达式:
import re
re.sub(r"\s", "", "foo bar\t")
其他回答
删除Python中的起始空格
string1 = " This is Test String to strip leading space"
print(string1)
print(string1.lstrip())
在Python中删除尾随空格或结束空格
string2 = "This is Test String to strip trailing space "
print(string2)
print(string2.rstrip())
在Python中,从字符串的开头和结尾删除空白空间
string3 = " This is Test String to strip leading and trailing space "
print(string3)
print(string3.strip())
删除python中的所有空格
string4 = " This is Test String to test all the spaces "
print(string4)
print(string4.replace(" ", ""))
另外,
"strip my spaces".translate( None, string.whitespace )
下面是Python3版本:
"strip my spaces".translate(str.maketrans('', '', string.whitespace))
对于Python 3:
>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'
...处理任何你没有想到的空白字符——相信我们,有很多。
\s本身总是覆盖ASCII空白:
(定期)空间 选项卡 新行(\n) 回车(\r) 换页 垂直制表符
另外:
对于启用了re.UNICODE的Python 2, Python 3,无需任何额外操作,
...\s还包括Unicode空白字符,例如:
插入空格, 他们的空间, 表意的空间,
…等。在“带有White_Space属性的Unicode字符”下面可以看到完整的列表。
但是\s不覆盖不属于空格的字符,这些字符实际上是空格,例如:
任意工匠, 蒙古语元音分隔符, 零宽度不间断空格(又称字节顺序标记),
…等。请在“没有White_Space属性的相关Unicode字符”下面查看完整列表。
所以这6个字符包含在第二个正则表达式的列表中,\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF。
来源:
https://docs.python.org/2/library/re.html https://docs.python.org/3/library/re.html https://en.wikipedia.org/wiki/Unicode_character_property
import re
re.sub(' ','','strip my spaces')
最简单的是使用replace:
"foo bar\t".replace(" ", "").replace("\t", "")
或者,使用正则表达式:
import re
re.sub(r"\s", "", "foo bar\t")