python用字符串之间的特殊字符替换空格

问题描述:

我想用'#'替换字符串之间的所有空格,除了字符串结尾之后的空格。python用字符串之间的特殊字符替换空格

实施例:

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

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

使用正则表达式。

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