andy garcia
andy garcia

Reputation: 25

When reversing a string converted from an int, the ending 0's are not being printed

For example:

num = 123401000

def reverse_int(num):
    sign = 1

    if num > 0:
        sign = 1
    else:
        sign = -1

    print(sign)
    tmp = abs(num)
    print(tmp)

    return int(str(tmp)[::-1]) * sign

print(reverse_int(num))

The purpose of this code is to print out the reverse of num, but this code prints out 104321. Can anyone tell me why the last zeros are not being captured?

Upvotes: 1

Views: 80

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114518

An integer naturally does not retain leading zeros in the way that a string does. 0001 is just 1. During the forward conversion, this is a good thing: 123401000 becomes '123401000', not '0000123401000'.

Putting it another way, there are an infinite number of leading zeros in any integer. There is no particular reason for Python to print any particular number of them (how does it know if you mean 001, 01 or 1?), so by default, leading zeros are not printed.

You have access to the correct number of leading zeros, so there's nothing stopping you from printing them correctly. You certainly don't need to return your number as a string, just keep track of the length of your intermediate string. Have your function return both the reversed integer and the desired print width:

def reverse_int(num):
    sign = 1 if num >= 0 else -1
    tmp = num * sign
    string = str(tmp)
    width = len(string) + (sign == -1)
    return int(string[::-1]) * sign, width

Now, using the correct format specifier, you can print your leading zeros:

num = 123401000
rev, width = reverse_int(num)
print(f'{rev:0{width}d}')

You could make this even more concise with the older format function:

print('{:0{}d}'.format(*reverse_int(num)))

You can even use the really old-school string interpolation operator:

print('%0*d' % (width, rev))

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155654

The zeros were captured. But when you converted it back to an int at the end, numerically there is no difference between 000104321 and 104321, and ints have only one native representation (001 and 1 are not going to be stored differently to keep the 0s). If you need to preserve those zeroes, you can't convert back to int, you have to leave it as a str.

An approach you could take would be to have sign store the prefix string, not a number, making your code:

def reverse_int(num):
    if num >= 0:
        sign = ''  # No sign to add
    else:
        sign = '-'  # Keep negative sign

    print(sign)
    tmp = abs(num)
    print(tmp)

    return sign + str(tmp)[::-1]

Upvotes: 2

Related Questions