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

时间:2013-03-10 17:06:23

标签: python

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

示例:

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

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

1 个答案:

答案 0 :(得分:2)

使用正则表达式。

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

但实际上,这更好:

output = re.sub(' ', '#', a.rstrip())
相关问题