在字符串中查找数字,添加1并替换

时间:2015-06-08 19:37:52

标签: python string digit

我需要编写一个代码,其中一个字符串包含一个数字,然后这个数字加1,然后在初始字符串输入中打印出来。

应该像这样工作

>>>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
到目前为止,我有这个,但我知道这是错误的,说实话,我不知道该怎么做。

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)

3 个答案:

答案 0 :(得分:3)

您可以在此使用re.sub

qs.annotate(
  num_x=Count('x', distinct=True),
  num_y=Count('y', distinct=True),
  num_x_per_y=num_x / num_y
)

另一个例子

>>> import re
>>> s = 'I have 366 friends on facebook'
>>> def addone(obj):
...     val = int(obj.group(1))
...     return str(val+1)
... 
>>> i = raw_input('what number would you like to increment?')
what number would you like to increment?6
>>> re.sub('({})'.format(i),addone,s)
'I have 377 friends on facebook'

您可以定义您的功能,如

>>> s = 'I slept 3 hours'
>>> i = raw_input('what number would you like to increment?')
what number would you like to increment?3
>>> re.sub('({})'.format(i),addone,s)
'I slept 4 hours'

但是我建议你有一个验证功能

def addNumber(s):
    def addone(obj):
        val = int(obj.group(1))
        return str(val+1)

    i = raw_input('what number would you like to increment?')
    return(re.sub('({})'.format(i),addone,s))

这将阻止用户输入超出范围的值

答案 1 :(得分:1)

根据您的要求,数值必须介于0到8之间,您可以使用string.replace

def increment(s, inc):
    return s.replace(str(inc), str(inc + 1))

>>> s = 'I have 366 friends on facebook'
>>> inc = 6
>>> increment(s, 6)
'I have 377 friends on facebook'

答案 2 :(得分:1)

代码中可能出现的错误是:

  1. 您正尝试直接替换int中的string类型数据。
  2. 同样只检查numbers.isdigit()将修改所有数字,无论您指定修改什么。
  3. 可能更正您的代码以使其正常运行:

    def incrementNumbers(statement):
        number1 = int(input('What number would you like to increment?'))
        number2 = number1 +1
        i=[]
        for numbers in statement:
            if numbers.isdigit() and int(numbers) == number1:
                i.append(numbers)
                statement.replace(numbers,str(number2))
    

    您还可以将incrementNumbers(statement)功能更改为:

    def incrementNumbers(statement):
        number1 = input('What number would you like to increment?')
        number2 = str(int(number1)+1)
        statement = statement.replace(number1,number2)
        return statement
    

    我认为比使用for循环更好。