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

probably at the beach
  • 14,489
  • 16
  • 75
  • 116
  • possible duplicate of [Python - Parse String to Float or Int](http://stackoverflow.com/questions/379906/python-parse-string-to-float-or-int) –  Apr 12 '11 at 13:12

3 Answers3

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'
eumiro
  • 207,213
  • 34
  • 299
  • 261
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'
gurney alex
  • 13,247
  • 4
  • 43
  • 57
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
Fenikso
  • 9,251
  • 5
  • 44
  • 72