Home > Net >  Converting '01' string to int prints only 1 why?
Converting '01' string to int prints only 1 why?

Time:04-02

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

CodePudding user response:

Integers cannot have leading zeros. If desired, you can add zeros after the operation and convert it to a string.
For example

a = "003"
b = "008"
c = str(int(a)   int(b)).zfill(3)
print(c)

Output

011

CodePudding user response:

Why? Because 0...01=1. That's basically why. Why store an int as 01 if you can just store 1? If you want to have the zeroes in front, you would have to convert back to string and add them, because 0001 is not an int.

CodePudding user response:

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
  • Related