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.

2
  • 4
    What happens with a 9? Commented Apr 27, 2011 at 8:58
  • @eumiro wraps to zero i guess, didn't think of that Commented Apr 27, 2011 at 9:04

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

ops, same solution.. i think you was faster than me
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

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.