[Python] How to convert alphabet to numbers?

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    Trying to convert alphabet to numbers. An example of what I'm trying to do is convert the word "green" to a list of corresponding number index values: [6, 17, 4, 4, 13]

    My eventual goal is to use it in a password encrypter thing, where I can convert the letters to numbers, do some math on the numbers so they're still on [0, 25], and then convert those numbers back to letters, so it's mixed up.

    Here's code of what I've done so far:

    def lettertonumber(word):
    flength = len(word)
    fcodera = "abcdefghijklmnopqrstuvwxyz"
    fcoderb = [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]
    fcoderlength = len(fcodera)
    numkey = []

    i = 0
    g = 0
    while i < flength: # flength is the length of 'word' (in the case of 'green', 5)
    while g < fcoderlength: # fcoderlength is the length of the alphabet (26)
    if word == fcodera[g]: # to convert it to the number
    numkey.append(fcoderb[g]) # fcoderb is a list with [0, 1, 2, 3... 24, 25] for the alphabet
    g = g + 1
    i = i + 1

    return numkey

    word = 'green'
    numberkey = lettertonumber(word)


    The output of print(numberkey) is [6]. My question, then, is considering the loops that I have, why am I only getting one iteration of the i loop worth of numbers in numberkey[], when I should be getting as many as the length of the word (so that print(numberkey) outputs [6, 17, 4, 4, 13])

    Sorry if my question is phrased poorly or unhelpful, this is my first question! Also sorry for my ignorance with Python -- I just learned it yesterday! Thank you!

    Continue reading...

Compartilhe esta Página