1

Is it possible to do something like this in Python using regular expressions?

Increment every character that is a number in a string by 1

So input "123ab5" would become "234ab6"

I know I could iterate over the string and manually increment each character if it's a number, but this seems unpythonic.

note. This is not homework. I've simplified my problem down to a level that sounds like a homework exercise.

Mike
  • 58,961
  • 76
  • 175
  • 221

3 Answers3

5
a = "123ab5"

b = ''.join(map(lambda x: str(int(x) + 1) if x.isdigit() else x, a))

or:

b = ''.join(str(int(x) + 1) if x.isdigit() else x for x in a)

or:

import string
b = a.translate(string.maketrans('0123456789', '1234567890'))

In any of these cases:

# b == "234ab6"

EDIT - the first two map 9 to a 10, the last one wraps it to 0. To wrap the first two into zero, you will have to replace str(int(x) + 1) with str((int(x) + 1) % 10)

eumiro
  • 207,213
  • 34
  • 299
  • 261
1

>>> test = '123ab5'
>>> def f(x):
        try:
            return str(int(x)+1)
        except ValueError:
            return x
 >>> ''.join(map(f,test))
     '234ab6'

sateesh
  • 27,947
  • 7
  • 36
  • 45
0
>>> a = "123ab5"
>>> def foo(n):
...     try: n = int(n)+1
...     except ValueError: pass
...     return str(n)
... 
>>> a = ''.join(map(foo, a))
>>> a
'234ab6'

by the way with a simple if or with try-catch eumiro solution with join+map is the more pythonic solution for me too

nkint
  • 11,513
  • 31
  • 103
  • 174