1

I currently have a pattern substitution that does the following:

x = re.sub('(\d+)','\g<1>','100')
=> x = 100

I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10

Thanks, Richard

1

3 Answers 3

6
import re

t = 'a b c 100 200'

f = lambda x: str(int(x.group(0)) / 10)
re.sub('\d+', f, t)

# returns 'a b c 10 20'
Sign up to request clarification or add additional context in comments.

Comments

1

you can do this by passing a function as 2nd argument to re.sub. That function will be called with a MatchObject :

>>> def repl(mo):
...    return mo.group(0)[:-1]
... 
>>> import re
>>> re.sub('\d+', repl, '100')
'10'

Comments

1

re.sub can take function as a second parameter.

import re

def func(r):
    return str(int(r.group(0)) / 10) 

x = re.sub("\d+", func, "100")
print x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.