Regular expression does not work in python. Removing spaces at the beginning of each line

I have variable text (in Python) with text to be printed in a file, and it has a lot of variable lengths, extra spaces at the beginning of most lines. All I want to do is remove these spaces. This is the code I used.

text = re.sub(r'(^\s*)',r'',text,re.MULTILINE)

However, only spaces on the first line are erased. Everything else remains as it is. Can someone tell me what I am doing wrong?

Many thanks.

+4
source share
4 answers

The fourth parameter re.subreplaces the counter, not the flag.

re.sub (pattern, repl, string, count = 0 , flags = 0)

>>> re.MULTILINE
8
>>> print re.sub(r'(^\s*)', '', '  a\n  b\n', re.MULTILINE)
a
  b    

flags.

>>> print re.sub(r'(^\s*)', '', '  a\n  b\n', flags=re.MULTILINE)
a
b

, :

>>> print re.sub(r'^\s*', '', '  a\n  b\n', flags=re.MULTILINE)
a
b

str.lstrip, .

>>> print '\n'.join(map(str.lstrip, '   a\n   b\n'.splitlines()))
a
b
+4

,

text = '\n'.join([line.lstrip() for line in text.splitlines()])

, . . Regexs, . .

+2

lstrip ?

file.write(content.lstrip())

, , , .

0

Boosting performance by avoiding regexes might not be readable in standby mode unless you do this on huge texts all the time. Otherwise, using a regular expression can lead to a simple understanding of the code:

sample_text = "    lorem ipsum\n" * 10
beginning_whitespace = re.compile(r'^\s+', flags=re.MULTILINE)
new_text = re.sub(beginning_whitespace, '', sample_text)

than, type of mysterious, other options:

new_text = '\n'.join([line.lstrip() for line in sample_text.split('\n')])
new_text = '\n'.join(map(str.lstrip, sample_text.splitlines()))
0
source

All Articles