mercredi 8 janvier 2020

Python list character replacement & duplication

I am just beginning to learn Python and want to clean up my code with two things:

  1. I am replacing characters in a word with numbers per the list I made. Is there a better way to do that with another for or while statement?
  2. If characters are replaced with the same number twice in a row, I need to keep only the first. How should I remove a duplicate in that case?
word = input("Enter a word to code: ")

for ch in range (0, len(word) - 1):

    letters = [('b','f','p','v'), ('c','g','j','k','q','s','x','z'),('d','t'),('l'),('m','n'),('r')]

    for ch in word:
        if ch in letters[0]:
            word = word.replace(ch,"1");
        if ch in letters[1]:
            word = word.replace(ch,"2");
        if ch in letters[2]:
            word = word.replace(ch,"3");
        if ch in letters[3]:
            word = word.replace(ch,"4");
        if ch in letters[4]:
            word = word.replace(ch,"5");
        if ch in letters[5]:
            word = word.replace(ch,"6");

Aucun commentaire:

Enregistrer un commentaire