标签归档:removing-whitespace

删除字符串中的所有空格

问题:删除字符串中的所有空格

我想消除字符串两端和单词之间的所有空白。

我有这个Python代码:

def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()

但这仅消除了字符串两侧的空白。如何删除所有空格?

I want to eliminate all the whitespace from a string, on both ends, and in between words.

I have this Python code:

def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()

But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?


回答 0

如果要删除开头和结尾的空格,请使用str.strip()

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

如果要删除所有空格字符,请使用str.replace()

(注意,这只会删除“常规” ASCII空格字符,' ' U+0020而不会删除任何其他空白

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

如果要删除重复的空格,请使用str.split()

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'

If you want to remove leading and ending spaces, use str.strip():

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

If you want to remove all space characters, use str.replace():

(NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace)

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

If you want to remove duplicated spaces, use str.split():

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'

回答 1

删除空格,请使用str.replace

sentence = sentence.replace(' ', '')

要删除所有空白字符(空格,制表符,换行符等),可以使用splitthen join

sentence = ''.join(sentence.split())

或正则表达式:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

如果只想从头到尾删除空格,则可以使用strip

sentence = sentence.strip()

您还可以lstrip用于仅从字符串的开头rstrip删除空格,并从字符串的结尾删除空格。

To remove only spaces use str.replace:

sentence = sentence.replace(' ', '')

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

sentence = ''.join(sentence.split())

or a regular expression:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

If you want to only remove whitespace from the beginning and end you can use strip:

sentence = sentence.strip()

You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.


回答 2

另一种选择是使用正则表达式并匹配这些奇怪的空白字符。这里有些例子:

删除字符串中的所有空格,即使单词之间也是如此:

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

在字符串的开头删除空格:

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)

删除字符串末尾的空格:

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)

删除字符串的开始和结尾处的空格:

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

删除仅重复的空格:

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))

(所有示例均可在Python 2和Python 3中使用)

An alternative is to use regular expressions and match these strange white-space characters too. Here are some examples:

Remove ALL spaces in a string, even between words:

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the BEGINNING of a string:

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the END of a string:

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)

Remove spaces both in the BEGINNING and in the END of a string:

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

Remove ONLY DUPLICATE spaces:

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))

(All examples work in both Python 2 and Python 3)


回答 3

空格包括空格,制表符和CRLF。因此,我们可以使用的一种优雅的单线字符串函数是str.translate

Python 3

' hello  apple'..translate(str.maketrans('', '', ' \n\t\r'))

或者,如果您想彻底了解:

import string
' hello  apple'..translate(str.maketrans('', '', string.whitespace))

Python 2

' hello  apple'.translate(None, ' \n\t\r')

或者,如果您想彻底了解:

import string
' hello  apple'.translate(None, string.whitespace)

Whitespace includes space, tabs, and CRLF. So an elegant and one-liner string function we can use is str.translate:

Python 3

' hello  apple'..translate(str.maketrans('', '', ' \n\t\r'))

OR if you want to be thorough:

import string
' hello  apple'..translate(str.maketrans('', '', string.whitespace))

Python 2

' hello  apple'.translate(None, ' \n\t\r')

OR if you want to be thorough:

import string
' hello  apple'.translate(None, string.whitespace)

回答 4

要从开头和结尾删除空格,请使用strip

>> "  foo bar   ".strip()
"foo bar"

For removing whitespace from beginning and end, use strip.

>> "  foo bar   ".strip()
"foo bar"

回答 5

' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})

MaK已经指出了上面的“翻译”方法。而且此变体适用于Python 3(请参阅此Q&A)。

' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})

MaK already pointed out the “translate” method above. And this variation works with Python 3 (see this Q&A).


回答 6

小心:

strip 执行rstrip和lstrip(删除前导和尾随空格,制表符,返回和换页,但不会在字符串中间删除它们)。

如果仅替换空格和制表符,则最终可能会出现隐藏的CRLF,这些CRLF似乎与您要查找的内容匹配,但并不相同。

Be careful:

strip does a rstrip and lstrip (removes leading and trailing spaces, tabs, returns and form feeds, but it does not remove them in the middle of the string).

If you only replace spaces and tabs you can end up with hidden CRLFs that appear to match what you are looking for, but are not the same.


回答 7

import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)
import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)

回答 8

此外,strip具有一些变化:

删除字符串的BEGINNING和END中的空格:

sentence= sentence.strip()

在字符串的开头删除空格:

sentence = sentence.lstrip()

删除字符串末尾的空格:

sentence= sentence.rstrip()

这三个字符串函数strip lstriprstrip都可以使用要删除的字符串参数,默认为全空格。当您处理某些特殊内容时,这可能会很有帮助,例如,您只能删除空格,而不能删除换行符:

" 1. Step 1\n".strip(" ")

或者,您可以在读取字符串列表时删除多余的逗号:

"1,2,3,".strip(",")

In addition, strip has some variations:

Remove spaces in the BEGINNING and END of a string:

sentence= sentence.strip()

Remove spaces in the BEGINNING of a string:

sentence = sentence.lstrip()

Remove spaces in the END of a string:

sentence= sentence.rstrip()

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

" 1. Step 1\n".strip(" ")

Or you could remove extra commas when reading in a string list:

"1,2,3,".strip(",")

回答 9

从字符串的两端和单词之间消除所有空格。

>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
    '', # replace with empty string (->remove)
    ''' hello
...    apple
... ''')
'helloapple'

Python文档:

eliminate all the whitespace from a string, on both ends, and in between words.

>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
    '', # replace with empty string (->remove)
    ''' hello
...    apple
... ''')
'helloapple'

Python docs: