Hedanito Hedanito - 6 months ago 21
Python Question

Remove tabs and spaces from start of each line

I have strings containing code that can have whitespace in front of it (tabs & spaces):

for foo in bar:
foo += 1
for i in range(0, foo):
print(foo * foo)


Since whitespace defines scope in python, this won't compile. So what is a good way to remove whitespace from the start of each line ONLY if it occurs on every line in the string, giving the following result:

for foo in bar:
foo += 1
for i in range(0, foo):
print(foo * foo)


The code is both generated and compiled in the same python program, so no other tools allowed.

Answer

The standard library's textwrap.dedent function does exactly what you want.

https://docs.python.org/3/library/textwrap.html#textwrap.dedent