Neb*_*sar 4 python regex replace
我想用nbsp;每个空格替换我的前导空格。
所以:
spam --> spam
eggs --> eggs
spam eggs --> spam eggs
Run Code Online (Sandbox Code Playgroud)
我见过一些使用正则表达式的解决方案,但都是其他语言的。我在 Python 中尝试过以下方法,但没有成功。
import re
raw_line = ' spam eggs'
line = re.subn('\s+', ' ', raw_line, len(raw_line))
print(line) # outputs spam eggs
line = re.sub('\s+', ' ', raw_line)
print(line) # outputs spam eggs
line = re.sub('^\s', ' ', raw_line)
print(line) # outputs spam eggs
line = re.sub('^\s+', ' ', raw_line)
print(line) # outputs spam eggs
Run Code Online (Sandbox Code Playgroud)
最后一行似乎最接近,但还没有雪茄。
在 Python中替换每个前导空格的正确方法是什么 ?
如果有一种干净的方法可以在没有正则表达式的情况下做到这一点,我会很乐意接受,但我自己无法弄清楚。
这里甚至不需要昂贵的正则表达式,只需删除前导空格并在前面添加一些 字符作为删除字符的数量:
def replace_leading(source, char=" "):
stripped = source.lstrip()
return char * (len(source) - len(stripped)) + stripped
print(replace_leading("spam")) # spam
print(replace_leading(" eggs")) # eggs
print(replace_leading(" spam eggs")) # spam eggs
Run Code Online (Sandbox Code Playgroud)