It is easy to convert 11 12 13 14
to 11a 12a 13a 14a
, using:
myStr = "11 12 13 14"
myStr = re.sub(r'(\d*)', r'\1a', myStr)
print myStr # 11a 12a 13a 14a
but how can I turn 11 12 13 14
to 12 13 14 15
by using re.sub
?
It is easy to convert 11 12 13 14
to 11a 12a 13a 14a
, using:
myStr = "11 12 13 14"
myStr = re.sub(r'(\d*)', r'\1a', myStr)
print myStr # 11a 12a 13a 14a
but how can I turn 11 12 13 14
to 12 13 14 15
by using re.sub
?
A regex solution with re.sub()
:
import re
string = "11 12 13 14"
def repl(m):
number = int(m.group(1)) + 1
return str(number)
print re.sub(r'\b(\d+)\b', repl, string)
# 12 13 14 15
See a demo on ideone.com.
As others mentioned, this might not be the most appropriate solution though.
The simplest approach for a string that only contains integer numbers separated with space is
s = "11 12 13 14"
print(" ".join([str(int(x)+1) for x in s.split()]))
# => 12 13 14 15
See the IDEONE demo
An alternative with a re.sub
can be used with the help of a \d+
regex pattern and a lambda in the replacement part:
import re
s = "11 12 13 14"
res = re.sub(r'\d+', lambda x: str(int(x.group()) + 1), s)
print(res) # => 12 13 14 15
The advantage of the regex approach is:
$
with \d+(?=\$)
or that are not part of float values with (?<!\d\.)\b\d+\b(?!\.\d)
)