2010-11-03 183 views
0

我需要改造的字符串:去掉空格

"There are 6 spaces in this string." 

到:

"Thereare6spacesinthisstring." 

回答

2

您可以使用替换():

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

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

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

如果你想去除所有的空白,包括标签:

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

不会re.subn是更好地处理空格?还是两个等价物? – 2010-11-03 06:31:33

+0

谢谢你尝试了以上替换版本没有运气,连接拆分解决方案是优雅的,像一个魅力... btw Python 3.2.3 – 2012-07-06 11:51:02

6

您可以使用replace

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

你da炸弹。非常感谢! – LJ3 2010-11-03 02:35:49

+5

LJ3:通过点击答案左边的复选标记来接受答案也是一件好事,以及您认为有用的答案答案 – 2010-11-03 02:41:15