python实现:本题要求编写程序,将输入字符串中的大写英文字母按以下对应规则替换,其他字符不变。(提示:转换表用元组实现)
时间: 2023-11-22 09:52:41 浏览: 316
以下是Python实现,使用了元组来实现对应规则的转换表:
```python
def replace_uppercase(s):
# 转换表,元组中每个元素表示一个对应关系,第一个元素为原字符,第二个元素为替换字符
convert_table = (
('A', 'Z'),
('B', 'Y'),
('C', 'X'),
('D', 'W'),
('E', 'V'),
('F', 'U'),
('G', 'T'),
('H', 'S'),
('I', 'R'),
('J', 'Q'),
('K', 'P'),
('L', 'O'),
('M', 'N'),
('N', 'M'),
('O', 'L'),
('P', 'K'),
('Q', 'J'),
('R', 'I'),
('S', 'H'),
('T', 'G'),
('U', 'F'),
('V', 'E'),
('W', 'D'),
('X', 'C'),
('Y', 'B'),
('Z', 'A'),
)
# 遍历字符串,将大写字母替换为对应字符
result = ''
for c in s:
if c.isupper():
for item in convert_table:
if c == item[0]:
result += item[1]
break
else:
result += c
return result
```
使用示例:
```python
s = 'Hello, World!'
result = replace_uppercase(s)
print(result) # 输出:Svool, Dliow!
```
阅读全文