所以我们有两个列表,a,它只由字母字符组成,b,它是用户对列表的输入。我正在尝试更改b关于它们在 中的索引a的字母字符,而不更改用户输入中的非字母字符。alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]a=input("Please enter a string: ")b=list(a)f=[]for elem in b: if elem in alphabet: c=alphabet.index(elem) d=(len(alphabet)-c) e=alphabet[d-1] f.append(e)mystring=''.join(f)print(mystring)我希望 abc123 的输出是 zyx123
2 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
考虑使用maketrans&str.translate似乎与您正在做的事情非常匹配:
intab = "abcdefghijklmnopqrstuvwxyz"
outtab = intab[::-1]
trantab = str.maketrans(intab, outtab)
str = "abc123";
print (str.translate(trantab))
>> zyx123
在上面,outtab变量只是使用python切片语法逆序的intab变量[::-1]
Maketrans 将一个列表中的所有字符转换为另一个列表中等效定位的字符。不在第一个列表中的任何字符都将单独保留。
添加回答
举报
0/150
提交
取消