mauguerra
mauguerra

Reputation: 3858

Find a number on a string using python

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

Answers (3)

hexparrot
hexparrot

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

Andrew Clark
Andrew Clark

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

jcollado
jcollado

Reputation: 40374

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.

Upvotes: 2

Related Questions