在Python 3.x中删除字符串中的空格

问题描述 投票:1回答:3

我需要转换字符串:

"There are 6 spaces in this string."

至:

"Thereare6spacesinthisstring."
python string python-3.x
3个回答
9
投票

你可以使用replace

string = "There are 6 spaces in this string"
string = string.replace(' ', '')

3
投票
new = "There are 6 spaces in this old_string.".replace(' ', '')

如果要删除所有空格,包括选项卡:

new = ''.join( old_string.split() )

2
投票

你可以使用replace():

print(string.replace(" ", ""))

您还可以使用rstrip,lstrip或strip删除结尾/开头(或两者!)的白色字符。

© www.soinside.com 2019 - 2024. All rights reserved.