Python 如何从字符串中去除所有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3739909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:30:19  来源:igfitidea点击:

How to strip all whitespace from string

pythonpython-3.xspacesstrip

提问by wrongusername

How do I strip all the spaces in a python string? For example, I want a string like strip my spacesto be turned into stripmyspaces, but I cannot seem to accomplish that with strip():

如何去除python字符串中的所有空格?例如,我希望将一个字符串strip my spaces变成stripmyspaces,但我似乎无法通过以下方式实现strip()

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

采纳答案by Tim Yates

Taking advantage of str.split's behavior with no sep parameter:

利用 str.split 没有 sep 参数的行为:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

如果您只想删除空格而不是所有空格:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

过早优化

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

尽管效率不是主要目标——编写清晰的代码才是——这里有一些初始时间:

$ 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

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this manytimes:

请注意,正则表达式已被缓存,因此它并不像您想象的那么慢。编译事前帮助一些,但在实践中,如果你把这个只会重要很多倍:

$ 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

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

尽管 re.sub 慢了 11.3 倍,但请记住,您的瓶颈肯定在其他地方。大多数程序不会注意到这 3 个选项中的任何一个之间的区别。

回答by Matthew Iselin

Try a regex with re.sub. You can search for all whitespace and replace with an empty string.

尝试使用正则表达式re.sub。您可以搜索所有空格并替换为空字符串。

\sin your pattern will match whitespace characters - and not just a space (tabs, newlines, etc). You can read more about it in the manual.

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

回答by carl

The simplest is to use replace:

最简单的是使用替换:

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

Alternatively, use a regular expression:

或者,使用正则表达式:

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

回答by Tim Yates

>>> import re
>>> re.sub(r'\s+', '', 'strip my spaces')
'stripmyspaces'

Also handles any whitespace characters that you're not thinking of (believe me, there are plenty).

还可以处理您没有想到的任何空白字符(相信我,有很多)。

回答by Dan Menes

Alternatively,

或者,

"strip my spaces".translate( None, string.whitespace )

And here is Python3 version:

这是 Python3 版本:

"strip my spaces".translate(str.maketrans('', '', string.whitespace))

回答by PrabhuPrakash

import re
re.sub(' ','','strip my spaces')

回答by Yogesh

As mentioned by Roger Pate following code worked for me:

正如 Roger Pate 所提到的,以下代码对我有用:

s = " \t foo \n bar "
"".join(s.split())
'foobar'

I am using Jupyter Notebook to run following code:

我正在使用 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

回答by JohnSmitoff

Remove the Starting Spaces in Python

删除 Python 中的起始空格

string1="    This is Test String to strip leading space"
print string1
print string1.lstrip()

Remove the Trailing or End Spaces in Python

删除 Python 中的尾随或结尾空格

string2="This is Test String to strip trailing space     "
print string2
print string2.rstrip()

Remove the whiteSpaces from Beginning and end of the string in Python

从 Python 中的字符串的开头和结尾删除空格

string3="    This is Test String to strip leading and trailing space      "
print string3
print string3.strip()

Remove all the spaces in python

删除python中的所有空格

string4="   This is Test String to test all the spaces        "
print string4
print string4.replace(" ", "")

回答by R. Arctor

TL/DR

TL/DR

This solution was tested using Python 3.6

此解决方案已使用 Python 3.6 进行测试

To strip all spaces from a string in Python3 you can use the following function:

要从 Python3 中的字符串中去除所有空格,您可以使用以下函数:

def remove_spaces(in_string: str):
    return in_string.translate(str.maketrans({' ': ''})

To remove any whitespace characters (' \t\n\r\x0b\x0c') you can use the following function:

要删除任何空白字符 (' \t\n\r\x0b\x0c'),您可以使用以下函数:

import string
def remove_whitespace(in_string: str):
    return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))

Explanation

解释

Python's str.translatemethod is a built-in class method of str, it takes a table and returns a copy of the string with each character mapped through the passed translation table. Full documentation for str.translate

Python 的str.translate方法是 str 的内置类方法,它接受一个表并返回字符串的副本,每个字符通过传递的转换表映射。str.translate 的完整文档

To create the translation table str.maketransis used. This method is another built-in class method of str. Here we use it with only one parameter, in this case a dictionary, where the keys are the characters to be replaced mapped to values with the characters replacement value. It returns a translation table for use with str.translate. Full documentation for str.maketrans

str.maketrans用于创建转换表。该方法是 的另一个内置类方法str。这里我们只使用一个参数,在这种情况下是字典,其中键是要替换的字符,映射到具有字符替换值的值。它返回一个用于str.translate. str.maketrans 的完整文档

The stringmodule in python contains some common string operations and constants. string.whitespaceis a constant which returns a string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.Full documentation for string

stringpython中的模块包含一些常见的字符串操作和常量。string.whitespace是一个常量,它返回一个包含所有被视为空白的 ASCII 字符的字符串。这包括字符空格、制表符、换行符、回车、换页和垂直制表符。字符串的完整文档

In the second function dict.fromkeysis used to create a dictionary where the keys are the characters in the string returned by string.whitespaceeach with value None. Full documentation for dict.fromkeys

在第二个函数dict.fromkeys中,用于创建一个字典,其中键是string.whitespace每个返回的字符串中的字符,并带有 value Nonedict.fromkeys 的完整文档

回答by jferard

The standard techniques to filter a list apply, although they are not as efficient as the split/joinor translatemethods.

过滤列表的标准技术适用,尽管它们不如split/jointranslate方法有效。

We need a set of whitespaces:

我们需要一组空格:

>>> import string
>>> ws = set(string.whitespace)

The filterbuiltin:

filter内置:

>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'

A list comprehension (yes, use the brackets: see benchmark below):

列表理解(是的,使用括号:参见下面的基准):

>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'

A fold:

折叠:

>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'

Benchmark:

基准:

>>> 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