'Add 1 to every second number

How do I add 1 to every second number?
Example:

2323 -> 2424
1112 -> 1213
3912 -> 31013

That is what I have now:

def plus_to_every_second(integer):
    integer = str(integer)
    integer_new = ''
    for i in integer:
        if integer.find(i) % 2 != 0:
            integer_new += str(int(i) + 1)
        else:
            integer_new += i

    return integer_new

For some reason, it does not work. But what is the actual solution?



Solution 1:[1]

This modified function should work:

def plus_to_every_second(integer):
    integer = str(integer)
    integer_new = ''
    for i in range(len(integer)):
      if i % 2 == 1:
        integer_new += str(int(integer[i]) + 1)
      else:
        integer_new += integer[i]
    return integer_new

First, as you did, we convert integer to a str and create a new variable, integer_new which holds an empty String.

However, in our for loop, we should iterate through integer so that we have access to the index.

If the index is odd (every second number), we then convert the character at that index to a number, add 1 to it, convert it back to a string, and then add it into integer_new.

If it's not at an odd index, then we just add the character into integer_new.

Solution 2:[2]

You won't have the best performance, but you can do the following for a quick solution:

>>> number = 3912
>>> digit_lst = list(str(number))
>>> digit_lst
['3', '9', '1', '2']
>>> new_digit_lst = [n if i % 2 == 0 else str(int(n)+1) for i, n in enumerate(digit_lst)]
>>> new_digit_lst
['3', '10', '1', '3']
>>> new_number = int(''.join(new_digit_lst))
>>> new_number
31013

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomerikoo
Solution 2 Alistair Celik