Home > OS >  Python: replace two or more spaces followed by a specified character with a single space followed by
Python: replace two or more spaces followed by a specified character with a single space followed by

Time:10-26

How do I replace two or more spaces followed by a specified character with a single space followed by that character, so that for example " &" become " &". I could successively run

str = str.replace("  &"," &")

but that is slow.

CodePudding user response:

Use reflex

import re
pattern = re.compile(r'  &')
string = '  &      &    h'
print(pattern.sub(' &', string))

Output

 & &    h

CodePudding user response:

replace one or more spaces with a single space:

import re
# match 1 or more spaces and then any non space character
pattern = re.compile(r'(\s )([^\s] )')
# replace with single space and keep second group
res = pattern.sub(r' \2', string)
  • Related