I need to write a code where a string contains a number, then this number is incremented by 1, and then printed out within the initial string input.
It should work like this
>>>addNumber('I slept 3 hours')
what number would you like to increment? 3
I slept 4 hours
>>>addNumber('I have 366 friends on facebook')
what number would you like to increment? 6
I have 377 friends on facebook
so far I have this, but I know it is wrong and honestly I don't know how to do this.
def incrementNumbers(statement):
number1=(int(input('What number would you like to increment?')))
number2 = number1 +1
i=[]
for numbers in statement:
if numbers.isdigit():
i.append(numbers)
statement.replace(numbers,number2)
Under your requirements that the numeric value must be between 0 and 8, you can use
string.replace
Possible error in your code is:
int
type data in thestring
directly.numbers.isdigit()
will modify all numbers irrespective of what you specified to modify.Possible corrections to your code to make it run properly:
You can also change your
incrementNumbers(statement)
function to:which I think is better than to use a
for
loop.You can use
re.sub
hereAnother Example
And you can define your function like
However I advice that you have a validation function
This will prevent the user from entering values outside your range