pythoncharacter-encodingasciichrord

Python Encoding Problems using ASCII Code


Write a function

shiftLetter(letter, n)

whose parameter, letter should be a single character. If the character is between "A" and "Z", the function returns an upper case character 𝑛 n positions further along, and "wrapping" if the + 𝑛 n mapping goes past "Z". Likewise, it should map the lower case characters between "a" and "z". If the parameter letter is anything else, or not of length 1, the function should return letter.

Hint: review functions ord() and chr() from the section, as well as the modulus operator %.


Down below is what I worked so far. It should return to A after alphabet is over, but it's not working properly from alphabet x. I guess..? I should subtract 90(Z) - 65(A) in ASCII table for x,y,z but confused about that.

def shiftLetter(letter,n):
    if letter >= 'A' and letter <= 'Z':
        return chr(ord(letter) + n )
   elif letter >= 'a' and letter <= 'z':
        return chr(ord(letter) + n )

print(shiftLetter('w',3))

Solution

  • You can use the mod operator to wrap the alphabet:

    def shiftLetter(letter,n):
       if letter >= 'A' and letter <= 'Z':
            return chr((ord(letter) - ord('A') + n) % 26 + ord('A') )
       elif letter >= 'a' and letter <= 'z':
            return chr((ord(letter) - ord('a') + n) % 26 + ord('a') )
    
    print(shiftLetter('w',3))   # z
    print(shiftLetter('E',3))   # H
    print(shiftLetter('Y',3))   # B
    print(shiftLetter('f',26))  # f
    print(shiftLetter('q',300)) # e
    

    Output

    z
    H
    B
    f
    e