1

I would like to keep the same amount of white space in my string but replace 'no' with empty string. Here is my code:

>>> import re
>>> line = '         no command'            
>>> line = re.sub('^\s.+no','',line) 
>>> line
' command'

Expected output without only 'no' replaced with empty string and the number of white spaces remain:

'         command'
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

3 Answers3

2

I think you want a positive look behind. It doesn't quite do exactly what your code does in terms of finding a match at the beginning of the line, but hopefully this sets you on the right track.

>>> line = '         no command'
>>> re.sub('(?<=\s)no','',line)
'          command'

You can also capture the preceding text.

>>> re.sub('^(\s.+)no', r'\1', line)
'          command'
rgher
  • 25
  • 5
2

Using .+ matches any character, so if you only want to match 1 or more whitespace characters you should repeat \s+ instead.

Then capture that in group 1 to be able to use that in the replacement and match no followed by a word boundary.

Note that \s can also match a newline.

import re

line = '         no command'
line = re.sub(r'^(\s+)no\b', r'\1', line)
print(line)

Output

command

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

what about using the replace method of the string class?

new_line = line.replace("no", "")
Johan Tuls
  • 105
  • 7