使用ASCII代码的Python编码问题

问题描述

编写函数

shiftLetter(letter,n)

其参数letter应该是单个字符。如果字符在"A""Z"之间,则该函数返回大写字符? ñ 位置更远,如果+?,则“包裹” ñ 映射经过"Z"。同样,它应在"a""z"之间映射小写字符。如果参数letter等于或不是长度1,则函数应返回letter

提示:请查看本节中的函数ord()chr()以及模量运算符%


下面是我到目前为止的工作。字母结束后,它应该返回到A,但是从字母x开始不能正常工作。我猜..?我应该在ASCII表中为x,y,z减去90(Z)-65(A),但对此感到困惑。

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))

解决方法

您可以使用mod运算符来包装字母:

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

输出

z
H
B
f
e