Home > other >  Incrementing digits in a string in python
Incrementing digits in a string in python

Time:10-26

Given a string, how can I increment that string by an x number, lets say I have 2345 and I want to increment each digit by 4 so that it is converted to 6789?

CodePudding user response:

Adding 4 units to each digit of 2345 is the same as adding 4444 to 2345.

For this you will have to convert the numbers to strings, but it is not a problem.

My proposed solution is something like this:

def my_func(number, digit_addition):
    number = str(number)
    digit_addition = str(digit_addition)
    
    number_addition = digit_addition * len(number)

    return int(number)   int(number_addition)

print(my_func(2345, 4))
#6789

CodePudding user response:

Here's my suggestion:

def add(number: str, addition: str) -> string:
    return [(int(item)   int(addition)) for item in number if (int(item)   int(addition)) < 10 else ((int(item)   int(addition)) - 10)].join()

add(5486, 2)

#7608

add(8913, 5)

#3468

CodePudding user response:

Computer memory works by holding blocks of tiny electrical charges (the famous 'ones and zeros' - really charge and no charge), so everything needs to represented using these. We need to somehow represent the number 6 or the letter p using these electrical charges.

We call one of these tiny electrical charges a bit, and 8 of them (normally) is a byte.

Python integers are represented in RAM directly as binary numbers, and they use four bytes. Imagine a 0 as no charge and 1 as a charge. For example the number 6 is represented in RAM as 00000000 00000000 00000000 00000110.

Strings are represented in RAM as binary numbers that represent UTF-8 characters. UTF-8 is a common way for characters (the letter p, the number 6, a smile emoji) to be represented in memory. The letter p is represented as 01110000, the number 6 is actually represented as 00110110 (54 in binary).

So telling the processor to add ...00000110 and ...00000110 would result in ...00001100, which is 12. Telling it to add 00110110 and 00110110 (two "6" strings) would come to 01101100 (108), which is actually a small letter l. This obviously makes no sense.

So, you need to convert the strings to integers (tell the python interpreter to turn 00110110 into 00000000 00000000 00000000 00000110), do the math, and then convert them back again:

num1 = "2345"
num2 = "4444"

ans = int(num1)   int(num2)
sring_ans = str(ans)

print(sring_ans)   // 6789
  • Related