Search code examples
pythonpython-3.xencoderletteralphabet

How to shift letters in the alphabet using python?


I want to shift each letter in the alphabet (e.g. a→b, b→c,...) using python. When you write a word like "Car", it shifts the letters and the new word is "Dbs"(C→D, a→b, r→s). Here is my code so far but it doesnt work and isn't very efficient:

def shift(letter):
      switch={
      "a":"b",
      "b":"c",
      "c":"d",
      "d":"e",
      "e":"f",
      "f":"g",
      "g":"h",
      "h":"i",
      "i":"j",
      "j":"k",
      "k":"l",
      "l":"m",
      "m":"n",
      "n":"o",
      "o":"p",
      "p":"q",
      "q":"r",
      "r":"s",
      "s":"t",
      "t":"u",
      "u":"v",
      "v":"w",
      "w":"x",
      "x":"y",
      "y":"z",
      "z":"a"
      }
      return switch.get(letter,"Invalid input")
      
shift("c")

Solution

  • You can use this:

    def shft_char(word,num):
        return ''.join(map(chr,([ord(c)+num for c in word])))
    

    Output:

    >>> shft_char('Car',1)
    'Dbs'