字符串到数字列表功能不起作用

时间:2013-03-29 16:52:56

标签: python string numbers

我是Python编程的新手,并且已经关注了一些视频和网站教程。我正在研究一些编程练习问题,但我在调试时遇到问题。这是我的第一次练习编程。该函数接受一个字符串并将其转换为数字列表。所以'a'变为0,'b'变为1,等等。它看起来非常简单,但我收到错误'IndexError:list index out of range'。我尝试了一些东西,但我不确定问题是什么。有人可以查看我的代码,看看我是否犯了任何明显的错误。非常感谢所有帮助!

    import sys
    import string
    import math

    def string2nlist(m):
    characters =    ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v''w''x''y''z']
    numbers = ['0''1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24''25']
    newList = []
    msgLen = len(m)         # var msgLen will be an integer of the length

    print 'Message before conversion: ' + m

    index = 0               # iterate through message length in while loop
    while index < msgLen:
        letter = m[index]   # iterate through message m
        i = 0
        while i < 26:
            if letter == characters[i]:
                newList[index] = numbers[i]
            i = i + 1
        index = index + 1
    print newList
    return newList


    message = 'hello'
    newMessage = string2nlist(message)

    print 'Message after conversion: ', newMessage

2 个答案:

答案 0 :(得分:0)

您的列表似乎格式不正确。尝试:

characters =    ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25']

答案 1 :(得分:0)

此:

characters = ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v''w''x''y''z']
numbers = ['0''1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24''25']

Python将相邻的字符串文字编译为单个字符串。这在许多情况下很有用,但不幸的是,这意味着它将您的列表转换为:

characters = ['abcdefghijklmnopqrstuvwxyz']
numbers = ['012345678910111213141516171819202122232425']

如前所述,在字符之间添加逗号。