本文介绍了删除字符串中的所有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想消除字符串两端和单词之间的所有空格.
I want to eliminate all the whitespace from a string, on both ends, and in between words.
我有这个 Python 代码:
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?
推荐答案
如果要删除前导和结尾空格,请使用 str.strip()
:
If you want to remove leading and ending spaces, use str.strip()
:
sentence = ' hello apple'
sentence.strip()
>>> 'hello apple'
如果要删除所有空格字符,请使用 str.replace()
:
If you want to remove all space characters, use str.replace()
:
(注意这只会删除正常"的 ASCII 空格字符 ' ' U+0020
而不是 任何其他空格)
(NB this only removes the "normal" ASCII space character ' ' U+0020
but not any other whitespace)
sentence = ' hello apple'
sentence.replace(" ", "")
>>> 'helloapple'
如果要删除重复的空格,请使用 str.split()
:
If you want to remove duplicated spaces, use str.split()
:
sentence = ' hello apple'
" ".join(sentence.split())
>>> 'hello apple'
这篇关于删除字符串中的所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!