在Python中删除字符串中的所有空格
我想从字符串的两端和单词之间消除所有空格。
我有这个Python代码:
def my_handle(self): sentence = ' hello apple '
sentence.strip()
但这仅消除了字符串两侧的空白。如何删除所有空格?
回答:
如果要删除开头和结尾的空格,请使用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'
以上是 在Python中删除字符串中的所有空格 的全部内容, 来源链接: utcz.com/qa/414442.html

