Python中不允许前导零?

v6ylcynt  于 4个月前  发布在  Python
关注(0)|答案(2)|浏览(73)

我有一个代码,用于查找列表中给定字符串的可能组合。但面临一个前导零错误的问题,如SyntaxError:不允许十进制整数字面量中的前导零;八进制整数使用0 o前缀。如何克服这个问题,因为我想传递前导零的值(无法始终手动编辑值)。下面是我的代码

def permute_string(str):
    if len(str) == 0:
        return ['']
    prev_list = permute_string(str[1:len(str)])
    next_list = []
    for i in range(0,len(prev_list)):
        for j in range(0,len(str)):
            new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1]
            if new_str not in next_list:
                next_list.append(new_str)
    return next_list

list = [129, 831 ,014]
length = len(list)
i = 0

# Iterating using while loop
while i < length:
    a = list[i]
    print(permute_string(str(a)))
    i += 1;

字符串

pxiryf3j

pxiryf3j1#

由于歧义,以0开头的整数 literals 在python中是非法的(显然,除了零本身)。以0开头的整数literals具有以下字符,该字符确定它福尔斯哪个数字系统:0x表示十六进制,0o表示八进制,0b表示二进制。
至于整数本身,它们只是数字,数字永远不会开始为零。如果你有一个整数表示为一个字符串,它碰巧有一个前导零,那么当你把它变成一个整数时,它会被忽略:

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

字符串
考虑到你在这里要做的事情,我只需要重写列表的初始定义:

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()


或者,如果你需要lst是一个整数列表,那么你可以通过使用格式字符串字面量来改变将它们转换为字符串的方式,而不是str()调用,这允许你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


在这个答案中,我使用lst作为变量名,而不是你问题中的list。你不应该使用list作为变量名,因为它也是表示内置列表数据结构的关键字,如果你命名一个变量,那么你就不能再使用关键字。

dba5bblo

dba5bblo2#

最后,我得到了我的答案。下面是工作代码。

def permute_string(str):
    if len(str) == 0:
        return ['']
    prev_list = permute_string(str[1:len(str)])
    next_list = []
    for i in range(0,len(prev_list)):
        for j in range(0,len(str)):
            new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1]
            if new_str not in next_list:
                next_list.append(new_str)
    return next_list

#Number should not be with leading Zero
actual_list = '129, 831 ,054, 845,376,970,074,345,175,965,068,287,164,230,250,983,064'
list = actual_list.split(',')
length = len(list)
i = 0

# Iterating using while loop
while i < length:
    a = list[i]
    print(permute_string(str(a)))
    i += 1;

字符串

相关问题