Convert alphabet letters to number in Python

后端 未结 16 1795
慢半拍i
慢半拍i 2020-11-28 05:09

How can the following be finished?

characters = [\'a\'\'b\'\'c\'\'d\'\'e\'\'f\'\'g\'\'h\'\'i\'\'j\'\'k\'\'l\'\'m\'\'n\'\'o\'\'p\'\'q\'\'r\'\'t\'\'u\'\'v\'\'w         


        
16条回答
  •  清酒与你
    2020-11-28 05:51

    If you are just looking to map a number to a letter, then just do something simple like this:

    def letter_to_index(letter):
        _alphabet = 'abcdefghijklmnopqrstuvwxyz'
        return next((i for i, _letter in enumerate(_alphabet) if _letter == letter), None)
    

    Of course if you want to have it start at 1, then just add (i+1 for i, ... etc.

提交回复
热议问题