我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
当前回答
用re.sub试试正则表达式。您可以搜索所有空白,并将其替换为空字符串。
模式中的\s将匹配空白字符,而不仅仅是空格(制表符,换行符等)。你可以在手册中读到更多的信息。
其他回答
下面是另一种使用普通列表理解的方法:
''.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'
最简单的是使用replace:
"foo bar\t".replace(" ", "").replace("\t", "")
或者,使用正则表达式:
import re
re.sub(r"\s", "", "foo bar\t")
正如Roger Pate所提到的,以下代码对我来说是有效的:
s = " \t foo \n bar "
"".join(s.split())
'foobar'
我正在使用Jupyter Notebook运行以下代码:
i=0
ProductList=[]
while i < len(new_list):
temp='' # new_list[i]=temp=' Plain Utthapam '
#temp=new_list[i].strip() #if we want o/p as: 'Plain Utthapam'
temp="".join(new_list[i].split()) #o/p: 'PlainUtthapam'
temp=temp.upper() #o/p:'PLAINUTTHAPAM'
ProductList.append(temp)
i=i+2
这个问题在面试中被问到。如果你要用条形法来解的话。这是一种方法
s='string with spaces'
res=''.join((i.strip(' ') for i in s))
print(res)
如果不需要最佳性能,你只想要一些非常简单的东西,你可以定义一个基本函数来测试每个字符,使用string类内置的"isspace"方法:
def remove_space(input_string):
no_white_space = ''
for c in input_string:
if not c.isspace():
no_white_space += c
return no_white_space
以这种方式构建no_white_space字符串不会有理想的性能,但解决方案很容易理解。
>>> remove_space('strip my spaces')
'stripmyspaces'
如果不想定义函数,可以将其转换为与列表推导式略有相似的内容。借用顶部答案的连接解决方案:
>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'