简体   繁体   中英

Python storing number with leading zeros in Dictionary

I have a dictionary called table. I want to assign this number to the below dic key. it keeps giving me an error saying "invalid token". I have tried converting it string, int, and float but to no avail

table['Fac_ID'] = 00000038058

you're unwilingly invoking Python 2.x octal mode but:

  • you can't because there's a 8 in it (bad or good luck?)
  • in python 3 (also works in python 2.7), octal prefix is no longer 0 but 0o : invalid token occurs because of that.

It would be better to store your values without leading zeroes and add the leading zeroes when you print them

print("%012d"%table['Fac_ID'])

Don't convert it to a string, use it as a string in the first place:

>>> table['Fac_ID'] = str(00000038058)
  File "<stdin>", line 1
    table['Fac_ID'] = str(00000038058)
                                    ^
SyntaxError: invalid token
>>> table['Fac_ID'] = '00000038058'
>>> print table['Fac_ID']
00000038058

str, as any function, evaluates the argument to a value before passing it in, so if there was an invalid token before str, using str is not going to change that. You need to use a valid token, so just hardcode the string.

Surround the number in quotes.

table['Fac_ID'] = "00000038058"

You can use zfill to pad zeros. Assuming you want to pad up to 11 zeroes:

>>> str(38058).zfill(11)
'00000038058'

This obviously creates a zero padded string to be used as the key based on an integer.

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