我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:

>>> 'strip my spaces'.strip()
'strip my spaces'

当前回答

这个问题在面试中被问到。如果你要用条形法来解的话。这是一种方法

s='string with spaces'
res=''.join((i.strip(' ') for i in s))
print(res)

其他回答

这个问题在面试中被问到。如果你要用条形法来解的话。这是一种方法

s='string with spaces'
res=''.join((i.strip(' ') for i in s))
print(res)

删除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(" ", ""))

下面是另一种使用普通列表理解的方法:

''.join([c for c in aString if c not in [' ','\t','\n']])

例子:

>>> aStr = 'aaa\nbbb\t\t\tccc  '
>>> print(aString)
aaa
bbb         ccc

>>> ''.join([c for c in aString if c not in [' ','\t','\n']])
'aaabbbccc'

用re.sub试试正则表达式。您可以搜索所有空白,并将其替换为空字符串。

模式中的\s将匹配空白字符,而不仅仅是空格(制表符,换行符等)。你可以在手册中读到更多的信息。

最简单的是使用replace:

"foo bar\t".replace(" ", "").replace("\t", "")

或者,使用正则表达式:

import re
re.sub(r"\s", "", "foo bar\t")