Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace 'nnn0n' with 'nnn1n' in Python using regular expressions

Tags:

python

regex

I would like to replace a string in form 'nnn0n' with the string in form 'nnn1n' where n is any digit. What the easiest way to do that? So, far I tried the following:

int(re.sub(r'^(\d+?)(0)(\d)$', r'\1???\3', '7001')) 

But what ever I insert in place of '???' either just 1 or \1 returns incorrect result.

Any ideas?

EDIT:

I have come up with an ugly version:

re.sub(r'a1a', '1', re.sub(r'^(\d+?)(0)(\d)$', r'\1a1a\3', '7001'))

Anything nicer?

like image 422
Andrey Adamovich Avatar asked Jul 25 '26 22:07

Andrey Adamovich


2 Answers

You can do something like:

re.sub(r'^(\d{3})0(\d)$', r'\g<1>1\2', '7001')

Or if it's not always three numbers before the 0 you want to replace:

re.sub(r'^(\d+)0(\d)$', r'\g<1>1\2', '1234509')

Edit If you know that the number will always be of the same format, you can just use:

re.sub(r'0(?=\d$)', '1', '7001')
like image 136
Qtax Avatar answered Jul 27 '26 12:07

Qtax


You don't really need regexes.

replace = lambda x: '{0}1{1}'.format(x[:-2], x[-1]) if x[-2] == '0' else x
# or: x[:-2] + '1' + x[-1]
print replace('12345678901')
like image 31
Cat Plus Plus Avatar answered Jul 27 '26 11:07

Cat Plus Plus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!