简体   繁体   中英

Keep zero digit save while converting string to integer in python

I am converting a string into integer using int function and it is working fine but i want to keep save zero digit that are at the start of the string.

string_value = '0123'
print(int(string_value))
result is 123

How can i format output 0123 as in integer type value not in string.

You can't, but if you want to put 0's (zero padding) at the beginning of your number, this is the way to do it.

"{:04}".format(123)
# '0123'

"{:05}".format(123)
# '00123'

Like every one said you can try above answers or the following :

string_value = '0123'
int_no = int(string_value)

print("%04d" % int_no)

print(string_value.zfill(4))

Both will give same answer

Impossible, you cannot get an integer value of 0123 .

You should change your mind, you do not actually need 0123 in integer, but you need to keep zero when displaying it. So the question should change to how to format output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM