在Python中删除字符串中的所有空白

2024-04-24 22:55:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有这个Python代码:

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

但这只会消除字符串两边的空白。如何删除所有空白?


Tags: 字符串代码selfapplehellomydef单词
3条回答

要仅删除空格请使用^{}

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

要删除所有空白字符(空格、制表符、换行符等),可以使用^{},然后使用^{}

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

或正则表达式:

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

如果只想删除开头和结尾的空白,可以使用^{}

sentence = sentence.strip()

您还可以使用^{}仅从字符串开头删除空白,使用^{}从字符串结尾删除空白。

另一种方法是使用正则表达式并匹配these strange white-space characters。下面是一些例子:

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

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)

如果要删除前导和结尾空格,请使用^{}

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

如果要删除所有空格字符,请使用^{}

(注意,这只删除“普通”ASCII空格字符' ' U+0020,而不删除any other whitespace

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

如果要删除重复的空格,请使用^{}

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

相关问题 更多 >