Skip to content
Advertisement

Converting ’01’ string to int prints only 1 why?

a='0'
print(int(a)) # OUTPUT IS 0
b='01'
print(int(b)) # OUTPUT IS 1
c='00111'     
print(int(c)) # OUTPUT IS 111

When i convert string ‘0’ to int and print it gives me 0 . But when i convert strings like ‘0111’ or ’01’ to int it only prints all 1 but not 0 why? and how to get that 0 , i tried lots of things but it dosent work

I want that when i give input in string like ‘0011’ and after converting this input in int it should give me output 0011

Advertisement

Answer

Here is a not entirely serious answer with a class which produces the output you were hoping for. This subclass of int counts the leading zeros in the string passed to the init method and stores it as an attribute. Then it uses it to generate the string representation.

Only for instructional purposes. Do not use.

The resulting objects can be added just like normal ints, however the result of additions, multiplications etc. are normal ints (no leading zeros). One would need to implement the __add__ dunder method in order to produce IntLeadingZeros from addition. And then the question becomes, how many leading zeros should the sum have?

I repeat, do not use.

class IntLeadingZeros(int):
    def __new__(self, value):
        return int.__new__(self, value)
    
    def __init__(self, value):
        int.__init__(value)
        self.nzeros = len(value) - len(value.lstrip('0')) if len(value) > 1 else 0

    def __str__(self):
        len_str = len(str(int(self)))
        return f"{int(self):0{len_str + self.nzeros}d}"
        

a='0'
print(IntLeadingZeros(a)) # OUTPUT IS 0
b='01'
print(IntLeadingZeros(b)) # OUTPUT IS 01
c='00111'     
print(IntLeadingZeros(c)) # OUTPUT IS 00111

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement