Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re.sub only replacing two occurrences [duplicate]

Tags:

python

regex

I am using re.sub but it is not replacing all occurrences.

re.sub(r'\b\s+\b', '.', string, re.I)

The first is the input and the second is the output.

a b c d e f g
a.b.c d e f g
like image 732
user1802143 Avatar asked Dec 09 '22 10:12

user1802143


2 Answers

You were telling it to replace only 2 instances:

>>> re.I
2
>>> re.sub(r'\b\s+\b', '.', string)
'a.b.c.d.e.f.g'
like image 55
Aziz Alfoudari Avatar answered Dec 11 '22 10:12

Aziz Alfoudari


To use the re.I flag, you should specify it as a keyword argument (or else it will be interpreted as being the value of count instead since count comes before flags in the signature of re.sub).

>>> string = 'a b c d e f g'
>>> re.sub(r'\b\s+\b', '.', string, flags=re.I)
'a.b.c.d.e.f.g'

Alternatively, compile your regex first.

>>> string = 'a b c d e f g'
>>> my_re = re.compile(r'\b\s+\b', re.I)
>>> re.sub(my_re, '.', string)
'a.b.c.d.e.f.g'
like image 25
senshin Avatar answered Dec 11 '22 10:12

senshin