为了账号安全,请及时绑定邮箱和手机立即绑定

Python 中不允许使用前导零?

Python 中不允许使用前导零?

弑天下 2023-03-22 16:13:44
我有一个代码用于查找列表中给定字符串的可能组合。但是面临前导零的问题,如SyntaxError: leading zeros in decimal integer literals is not allowed; 对八进制整数使用 0o 前缀。如何解决这个问题,因为我想传递带有前导零的值(不能一直手动编辑值)。下面是我的代码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_listlist = [129, 831 ,014]length = len(list)i = 0# Iterating using while loopwhile i < length:    a = list[i]    print(permute_string(str(a)))    i += 1;
查看完整描述

2 回答

?
开满天机

TA贡献1786条经验 获得超12个赞

由于歧义,以 0 开头的整数文字在 python 中是非法的(显然除了零本身)。以 0 开头的整数文字具有以下字符,用于确定它属于哪个数字系统: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(),这允许您用零填充数字:


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作为变量名,因为它也是代表内置列表数据结构的关键字,如果你命名一个变量那么你就不能再使用关键字。


查看完整回答
反对 回复 2023-03-22
?
jeck猫

TA贡献1909条经验 获得超7个赞

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


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;


查看完整回答
反对 回复 2023-03-22
  • 2 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信