user469652 user469652 - 1 year ago 45
Python Question

Python: use regular expression to remove the white space from all lines

^(\s+) only removes the whitespace from the first line, how to remove the front whitespace from all the lines?


Python's regex module does not default to multi-line ^ matching, so you need to specify that flag explicitly.

r = re.compile(r"^\s+", re.MULTILINE)
r.sub("", "a\n b\n c") # "a\nb\nc"

# or without compiling (only possible for Python 2.7+ because the flags option
# didn't exist in earlier versions of re.sub)

re.sub(r"^\s+", "", "a\n b\n c", flags = re.MULTILINE)

# but mind that \s includes newlines:
r.sub("", "a\n\n\n\n b\n c") # "a\nb\nc"

It's also possible to include the flag inline to the pattern:

re.sub(r"(?m)^\s+", "", "a\n b\n c")