Python数字到字转换器需要空间检测器

时间:2014-04-19 13:00:20

标签: python indexing converter

我一直在使用python中的一种加密工具。这段代码用于解密功能。

重点是获取给定的数字并将它们插入一个列表中,它们将被给定的键除以。

我对代码的想法如下,但每当我尝试时,我都会收到out of list index range。有什么建议?请记住,我是初学者:

need = []
detr = raw_input('What would you like decrypted?')
count = 0
for d in detr:
    if (d == '.' or d == '!') or (d.isalpha() or d== " "):
        count +=1
    else:
        need[count].append(d)   

2 个答案:

答案 0 :(得分:0)

问题是您正在尝试覆盖不存在的列表值。

list.append(item)item添加到list的末尾。 list[index] = item会在list位置index中插入项目。

list = [0,0,0]
list.append(0) # = [0,0,0,0]
list[0] = 1 # [1,0,0,0]
list[99] = 1 # ERROR: out of list index range

你应该完全摆脱count变量。您可以在None等情况下附加d==' ',或者只是忽略它们。

答案 1 :(得分:0)

我理解你的描述的方式是你想要在字符串中提取数字并使用for循环将它们附加到列表中以迭代每个字符。

我认为使用正则表达式(类似r'([\d]+)')会更容易。 但joconner说道:"摆脱计数变量"

need = []
detr = input('What would you like decrypted?\n')
i = iter(detr) # get an iterator
# iterate over the input-string
for d in i:
    numberstr = ""
    try:
        # as long as there are digits
        while d.isdigit():
            # append them to a cache-string
            numberstr+= d
            d = next(i)
    except StopIteration:
            # occurs when there are no more characters in detr
            pass
    if numberstr != "":
        # convert the cache-string to an int
        # and append the int to the need-array  
        need.append( int(numberstr) )

# print the need-array to see what is inside
print(need)