我该如何在Python字符串中删除所有空格?例如,我想将像strip my spaces
这样的字符串转换为stripmyspaces
,但似乎无法使用strip()
实现:
>>> 'strip my spaces'.strip()
'strip my spaces'
我该如何在Python字符串中删除所有空格?例如,我想将像strip my spaces
这样的字符串转换为stripmyspaces
,但似乎无法使用strip()
实现:
>>> 'strip my spaces'.strip()
'strip my spaces'
简述
本解决方案已使用Python 3.6测试。
要从Python3中的字符串中去除所有空格,可以使用以下函数:
def remove_spaces(in_string: str):
return in_string.translate(str.maketrans({' ': ''})
import string
def remove_whitespace(in_string: str):
return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))
解释
Python的str.translate
方法是str的一个内置类方法,它接受一个表格并返回通过传递的翻译表映射每个字符的字符串副本。str.translate的完整文档
要创建翻译表,使用str.maketrans
。这个方法是str
的另一个内置类方法。在这里,我们只使用了一个参数,即字典,在这种情况下,键是要替换的字符,映射到具有字符替换值的值。它返回用于与str.translate
一起使用的翻译表。str.maketrans的完整文档
string
模块包含一些常见的字符串操作和常量。string.whitespace
是一个常量,返回一个包含所有被认为是空格的ASCII字符的字符串。这包括空格、制表符、换行符、回车符、换页符和垂直制表符等字符。string.whitespace的完整文档
在第二个函数中,使用dict.fromkeys
创建一个字典,其中键是由string.whitespace
返回的字符串中的字符,每个键的值为None
。dict.fromkeys的完整文档
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
解决方案中借鉴:>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'
s='string with spaces'
res=''.join((i.strip(' ') for i in s))
print(res)
这里有另一种使用普通的列表推导式的方法:
''.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'