Home > Mobile >  How check if first digit of integer is zero in python
How check if first digit of integer is zero in python

Time:04-06

** i want to check if first digit of integer is zero. If it is zero, i want to leave first digit which is zero and take the rest. For example num = 0618861552 In this case first digit is zero. I want to get 618861552

If the first digit of num is not zero, i want to take the entire string.

For example num = 618861552 In this case first digit of num is not zero, i want to get 618861552

Below is the code i have tried.

Note that my code works if first digit is not zero but doesn't work if the first digit is zero **

num =  int(input("enter number: "))

#changing int to str to index.

position  = str(num)

if int(position[0]) == 0:
    len = len(position)
    position1 = position[1:len] 
    print(position1)
else:
    len = len(position)
    position1 = position [0:len]
    print(position1)

CodePudding user response:

This should do:

number = input("enter number: ")
print(number.lstrip('0'))

CodePudding user response:

This would work :

def remove_zero (a) :
    a = str(a)
    if ord(a[0]) == 48 :
        a = a[1:]
    return (str(a))

p = int(input("Enter a number :"))
q = remove_zero(p)
print(q)

CodePudding user response:

Actually converting to int remove all leading zero.

num = "0020"
num2 = "070"
num3 = "000000070"
print(int(num))
print(int(num2))
print(int(num3))

Output is

20
70
70

And this way works too:

num = int(input())
print(num)

That is why

Note that my code works if first digit is not zero but doesn't work if the first digit is zero **

It is always without leading zero after convertion to int

  • Related