0

I am working on a python function. I have a given string and I need to find if there is a number on that string, and then add 1 to that number. (any number from 1 to 100).

I found the "find", or the "count" function but what they do (as I understand) is to find a specific letter or number. On my function, I dont know which number I am looking for, so I dont know how to use those functions.

Example 1:

# WHAT I HAVE    
string = "STRING 2"
# WHAT I WANT AS A RESULT
STRING 3

Example 2:

# WHAT I HAVE
string = "STRING 9 STRING"
# WHAT I WANT AS A RESULT
STRING 10 STRING

Does anyone knows how to do this? Thanks a lot!

2
  • 2
    I've added the homework tag, please feel free to remove it if this isn't. Commented Feb 15, 2012 at 23:18
  • Actually is not for homework, is for work, but I am starting with python. But I think this may help. Thanks Commented Feb 15, 2012 at 23:22

3 Answers 3

2
import re

def increment_repl(match):
    return str(int(match.group(0)) + 1)

def increment_ints(s):
    return re.sub(r'-?\d+', increment_repl, s)

>>> increment_ints("STRING 2")
'STRING 3'
>>> increment_ints("STRING 9 STRING")
'STRING 10 STRING'
>>> increment_ints("-1 0 1 2")
'0 1 2 3'
Sign up to request clarification or add additional context in comments.

2 Comments

It worked very well. Thanks a lot. What happens if the string does not have any number?
Then re.sub() will not find any matches and the string will be returned unchanged.
2

In my opinion the best way to do that would be to use a re.sub to make the replacement.

In particular, note that the repl argument can be a callable, so it would be very easy to write a function that adds one to an integer.

Comments

2

If you prefer a regular-expression free solution:

string = "STRING 9 STRING"

def increment(val):
    if val.isdigit():
        return str(int(val) + 1)
    return val

newstring = [increment(i) for i in string.split()]
print " ".join(newstring)

1 Comment

"-1".isdigit() evaluates to false.

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.