[英]Leading zeros are not allowed in Python?
我有一个代码用于查找列表中给定字符串的可能组合。 但是面临前导零出现错误的问题,例如SyntaxError:leading zeros in decimal integer literals are 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_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;
由于歧义,Integer 以 0 开头的文字在 python 中是非法的(显然,除了零本身)。 以 0 开头的 integer 文字具有以下字符,该字符确定它属于哪个数字系统: 0x
表示十六进制, 0o
表示八进制, 0b
表示二进制。
至于整数本身,它们只是数字,数字永远不会从零开始。 如果您有一个 integer 表示为一个字符串,并且它恰好有一个前导零,那么当您将它转换为 integer 时,它将被忽略:
>>> 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
作为变量名,因为它也是表示内置列表数据结构的关键字,如果您命名了一个变量,那么您就不能再使用该关键字。
最后,我得到了我的答案。 下面是工作代码。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.