删除Python字符串中的所有空格我想消除字符串中的所有空格,在两端和单词之间。我有以下Python代码:def my_handle(self):
sentence = ' hello apple '
sentence.strip()但这只会消除字符串两边的空格。如何删除所有空白?
3 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
str.strip()
:
sentence = ' hello apple'sentence.strip()>>> 'hello apple'
str.replace()
:
sentence = ' hello apple'sentence.replace(" ", "")>>> 'helloapple'
str.split()
:
sentence = ' hello apple'" ".join(sentence.split())>>> 'hello apple'
千巷猫影
TA贡献1829条经验 获得超7个赞
str.replace
:
sentence = sentence.replace(' ', '')
split
join
:
sentence = ''.join(sentence.split())
import re pattern = re.compile(r'\s+')sentence = re.sub(pattern, '', sentence)
strip
:
sentence = sentence.strip()
lstrip
rstrip
添加回答
举报
0/150
提交
取消