2013-03-10 261 views
0

我想用'#'替換字符串之間的所有空格,除了字符串結尾之後的空格。python用字符串之間的特殊字符替換空格

實施例:

input=' hello world ' 
output = '#hello##world' 

我知道使用rstrip()我可以忽略在字符串的末尾的空間。我只想嘗試不使用rstrip()

回答

2

使用正則表達式。

import re 
a = ' hello world ' 
a = re.sub(' +$', '', a) 
output = re.sub(' ', '#', a) 

但實際上,這是更好的:

output = re.sub(' ', '#', a.rstrip()) 
+0

你不需要'應用re.sub()'在最後一個例子:'s.rstrip( 「 」).replace(「」 ,「#」)'。要替換任何空格:'re.sub(r「\ s」,「#」,s.rstrip())' – jfs 2013-03-10 17:53:32