4
p = r'([\,|\.]\d{1}$)'
re.sub(p, r"\1", v)

works, but I want to add a zero to the capture group, not replace with capture group '10', how can I do this?

re.sub(p, r"\10", v)

fails:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 275, in filter
    return sre_parse.expand_template(template, match)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py", line 802, in expand_template
    raise error, "invalid group reference"
sre_constants.error: invalid group reference
RabbitInAHole
  • 521
  • 4
  • 12

3 Answers3

6

Just wrap the group reference in '\g<#>':

import re
pattern = r'([\,|\.]\d{1}$)'
string = 'Some string .1\n'
rep = r'\g<1>0'
re.sub(pattern, rep, string)
> 'Some string .10\n'

Source: http://docs.python.org/2/library/re.html#re.sub

qstebom
  • 589
  • 3
  • 12
1

Use a named capture group:

p = r'(?P<var>[\,|\.]\d{1})$'
re.sub(p, r"\g<var>0", v)

e.g.

>>> p = r'(?P<var>[\,|\.]\d{1})$'
>>> v = '235,5'
>>> re.sub(p, r"\g<var>0", v)
'235,50'
Hedde van der Heide
  • 19,278
  • 13
  • 58
  • 93
0

The simplest method (which might also be the only method, I'm not actually sure) is to name the capturing group, then refer back to it by name:

>>> re.sub(p, r'\10', '1.2')
Traceback (most recent call last):
   ...
sre_constants.error: invalid group reference
>>> p = r'(?P<frac>[\,|\.]\d{1}$)'
>>> re.sub(p, r'\g<frac>0', '1.2')
'1.20'

Pick some name better than just "frac" (which I pulled out my ... er, ear, yes, let's go with "ear" :-) ).

Chris

torek
  • 330,127
  • 43
  • 437
  • 552