python用特殊字符替换字符串之间的空格
我想把字符串中所有的空格替换成'#',除了字符串末尾的空格。
举个例子:
input=' hello world '
output = '#hello##world'
我知道用 rstrip()
可以忽略字符串末尾的空格。我只是想试试不使用 rstrip()
的方法。
1 个回答
2
使用正则表达式。
import re
a = ' hello world '
a = re.sub(' +$', '', a)
output = re.sub(' ', '#', a)
不过,实际上,这个方法更好:
output = re.sub(' ', '#', a.rstrip())