如何去除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'
在没有 sep 参数的情况下利用 str.split 的行为:
>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
如果您只想删除空格而不是所有空格:
>>> s.replace(" ", "")
'\tfoo\nbar'
尽管效率不是主要目标——编写清晰的代码才是——这里有一些初始时间安排:
$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop
请注意,正则表达式是缓存的,所以它没有你想象的那么慢。事先编译它会有所帮助,但只有在你多次调用它时才会在实践中发挥作用:
$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop
尽管 re.sub 慢了 11.3 倍,但请记住,您的瓶颈肯定在其他地方。大多数程序不会注意到这三个选项之间的区别。
对于 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 空白:
此外:
re.UNICODE
启用的 Python 2,...\s
还涵盖了 Unicode 空白字符,例如:
...ETC。请参阅此处的完整列表,在“具有 White_Space 属性的 Unicode 字符”下。
但是\s
,不包括未被归类为空格的字符,这些字符实际上是空格,例如:
...ETC。请参阅此处的完整列表,在“没有 White_Space 属性的相关 Unicode 字符”下。
所以这 6 个字符被第二个正则表达式中的列表覆盖,\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF
.
资料来源:
或者,
"strip my spaces".translate( None, string.whitespace )
这是 Python3 版本:
"strip my spaces".translate(str.maketrans('', '', string.whitespace))
最简单的是使用替换:
"foo bar\t".replace(" ", "").replace("\t", "")
或者,使用正则表达式:
import re
re.sub(r"\s", "", "foo bar\t")
string1 = " This is Test String to strip leading space"
print(string1)
print(string1.lstrip())
string2 = "This is Test String to strip trailing space "
print(string2)
print(string2.rstrip())
string3 = " This is Test String to strip leading and trailing space "
print(string3)
print(string3.strip())
string4 = " This is Test String to test all the spaces "
print(string4)
print(string4.replace(" ", ""))
正如 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
尝试使用re.sub
. 您可以搜索所有空格并替换为空字符串。
\s
在您的模式中将匹配空白字符 - 而不仅仅是空格(制表符、换行符等)。您可以在手册中阅读有关它的更多信息。
过滤列表的标准技术适用,尽管它们不如split/join
ortranslate
方法有效。
我们需要一组空格:
>>> import string
>>> ws = set(string.whitespace)
filter
内置:
>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'
列表理解(是的,使用方括号:请参阅下面的基准):
>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'
一折:
>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'
基准:
>>> from timeit import timeit
>>> timeit('"".join("strip my spaces".split())')
0.17734256500003198
>>> timeit('"strip my spaces".translate(ws_dict)', 'import string; ws_dict = {ord(ws):None for ws in string.whitespace}')
0.457635745999994
>>> timeit('re.sub(r"\s+", "", "strip my spaces")', 'import re')
1.017787621000025
>>> SETUP = 'import string, operator, functools, itertools; ws = set(string.whitespace)'
>>> timeit('"".join([c for c in "strip my spaces" if c not in ws])', SETUP)
0.6484303600000203
>>> timeit('"".join(c for c in "strip my spaces" if c not in ws)', SETUP)
0.950212219999969
>>> timeit('"".join(filter(lambda c: c not in ws, "strip my spaces"))', SETUP)
1.3164566040000523
>>> timeit('"".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))', SETUP)
1.6947649049999995
import re
re.sub(' ','','strip my spaces')
TL/DR
此解决方案已使用 Python 3.6 进行了测试
要从 Python3 中的字符串中去除所有空格,可以使用以下函数:
def remove_spaces(in_string: str):
return in_string.translate(str.maketrans({' ': ''})
要删除任何空白字符('\t\n\r\x0b\x0c'),您可以使用以下函数:
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
python中的模块包含一些常见的字符串操作和常量。string.whitespace
是一个常量,它返回一个字符串,其中包含所有被视为空白的 ASCII 字符。这包括字符空格、制表符、换行符、回车符、换页符和垂直制表符。字符串的完整文档
在第二个函数dict.fromkeys
中,用于创建一个字典,其中键是每个返回的字符串中的字符string.whitespace
value None
。dict.fromkeys 的完整文档
如果不需要最佳性能并且您只是想要一些简单的东西,您可以定义一个基本函数来使用字符串类的内置“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
解决方案:
>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'
最后一行代码:
' '.join(word.strip() for word in message_text.split()