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

4 投票
3 回答
20507 浏览
提问于 2025-04-16 06:28

我需要把这个字符串:

"There are 6 spaces in this string."

转换成:

"Thereare6spacesinthisstring."

3 个回答

2

你可以使用 replace() 方法来替换字符串中的内容:

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

你还可以用 rstrip、lstrip 或 strip 方法来删除字符串开头或结尾(或者两者都删)的空白字符。

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

如果你想去掉所有的空白字符,包括制表符(Tab键产生的空格):

15

你可以使用 replace 这个功能。

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

撰写回答