Home > Blockchain >  Replace string with same amount of white spaces in search pattern
Replace string with same amount of white spaces in search pattern

Time:09-28

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'

CodePudding user response:

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'

CodePudding user response:

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

CodePudding user response:

what about using the replace method of the string class?

new_line = line.replace("no", "")
  • Related