以下程序实现了一种简单的“翻转”加密:将大写字母表中的每个字母替换为与其对称的字母( A ↔ Z 、 B ↔ Y 、 C ↔ X 、……)。横线处填写的代码是?( ) text = "HELLO" result = [] for ch in text: if 'A' <= ch <= 'Z': ____________ result.append(new_ch) else: result.append(ch) encrypted = ''.join(result) print(encrypted)
A:new_ch = chr(ord('Z') - (ord(ch) - ord('A')))
B:new_ch = chr(ord('Z') - ord(ch) - ord('A'))
C:new_ch = chr(ord('Z') + (ord(ch) - ord('A')))
D:new_ch = chr(ord('Z') - ord(ch))
正确答案:A
答案解析
遍历字符串中的每个字符,判断是否为大写字母。若是,则计算其在字母表中的正向位置偏移量(相对于'A'),再通过该偏移量从'Z'开始反向定位对应字符。利用ASCII码值进行转换:先用ord获取字符数值,计算目标字符的数值,再用chr转回字符。非大写字母不参与变换。结果需将每个处理后的字符收集。
试卷来源:202606 CCF-GESP编程能力等级认证Python三级真题