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

时间:2010-11-03 02:23:38

标签: python string python-3.x

我需要转换字符串:

"There are 6 spaces in this string."

为:

"Thereare6spacesinthisstring."

3 个答案:

答案 0 :(得分:8)

您可以使用replace

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

答案 1 :(得分:3)

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

如果要删除所有空格,包括标签:

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

答案 2 :(得分:2)

您可以使用replace():

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

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