Replace Leading Whitespace With Other Other Char - Python
I want to replace my leading whitespace with a nbsp; per whitespace. So: spam --> spam eggs --> eggs spam eggs --> spam eggs I've seen a
Solution 1:
You don't even need expensive regex here, just strip out the leading whitespace and prepend a number of
characters for the number of stripped characters:
defreplace_leading(source, char=" "):
stripped = source.lstrip()
return char * (len(source) - len(stripped)) + stripped
print(replace_leading("spam")) # spamprint(replace_leading(" eggs")) # eggsprint(replace_leading(" spam eggs")) # spam eggs
Solution 2:
You can use re.sub
with a callback function and evaluate the length of the match:
>>>raw_line = ' spam eggs'>>>re.sub(r"^\s+", lambda m: " " * len(m.group()), raw_line)
' spam eggs'
Post a Comment for "Replace Leading Whitespace With Other Other Char - Python"