Leading zeros are not allowed in Python?

Integer literals starting with 0 are illegal in python (other than zero itself, obviously), because of ambiguity. An integer literal starting with 0 has the following character which determines what number system it falls into: 0x for hex, 0o for octal, 0b for binary.

As for the integers themselves, they’re just numbers, and numbers will never begin with zero. If you have an integer represented as a string, and it happens to have a leading zero, then it’ll get ignored when you turn it into an integer:

>>> print(int('014'))
14

Given what you’re trying to do here, I’d just rewrite the list’s initial definition:

lst = ['129', '831', '014']
...
while i < length:
    a = lst[i]
    print(permute_string(a))  # a is already a string, so no need to cast to str()

or, if you need lst to be a list of integers, specifically, then you can change how you convert them to strings by using a format-string literal, instead of the str() call, which allows you to pad the number with zeros:

lst = [129, 831, 14]
...
while i < length:
    a = lst[i]
    print(permute_string(f'{a:03}'))  # three characters wide, add leading 0 if necessary

throughout this answer, I use lst as the variable name, instead of the list in your question. You shouldn’t use list as a variable name, because it’s also the keyword that represents the built-in list datastructure, and if you name a variable that then you can no longer use the keyword.

Leave a Comment