2010-11-03 76 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