Reputation: 3858
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!
Upvotes: 0
Views: 536
Reputation: 3417
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)
Upvotes: 2
Reputation: 208465
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'
Upvotes: 2