我试图修改一段文本,以应用以下翻译:
before: abcdefghijqlmnopqrstuvwxyz
after: zyxwvutsrqponmlkjihgfedcba也就是说,每个a变成一个z;每个b变成一个y;每个c变成一个x;依此类推。
我的剧本:
myInput = input("Entrer une chaine de caracteres:\n\n")
myInputSansEspace = myInput.replace(" ", "")
myInputAsciiInverse = myInputSansEspace.replace("a","z").replace("b","y").replace("c","x").replace("d","w").replace("e","v").replace("f","u").replace("g","t").replace("h","s").replace("i","r").replace("j","q").replace("k","p").replace("l","o").replace("m","n").replace("n","m").replace("o","l").replace("p","k").replace("q","j").replace("r","i").replace("s","h").replace("t","g").replace("u","f").replace("v","e").replace("w","d").replace("x","c").replace("y","b").replace("z","a")
print(myInputAsciiInverse)不幸的是它不起作用了。例如,如果我写:
我是诺伯
回报应是:
雷兹姆利
因为i被r取代;a被z取代;m被n取代;等等。
我得到的结果是:
布尼麦
发布于 2017-02-05 04:27:25
你的方法有副作用,所以不做你想做的事。
采取你的第一个替代:
'a...z'.replace('a', 'z') == 'z...z'现在考虑最后一个替换:
'z...z'.replace('z', 'a') == 'a...a'因此,最终只有一半的字母表。
您只需将所有replace替换为reverse或切片:
'abc..xyz'.reverse() == 'zyx..cba'
'abc..xyz'[::-1] == 'zyx..cba'如果您试图将翻译作为密码的一种方式,那么您可以使用str.maketrans和str.translate,例如:
>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> trans = str.maketrans(alphabet, alphabet[::-1], ' ')
>>> noob = 'I am noob'
>>> noob.lower().translate(trans)
'rznmlly'注意:alphabet等同于string.ascii_lowercase
以上内容大致相当于:
>>> import string
>>> trans_table = dict(zip(string.ascii_lowercase, string.ascii_lowercase[::-1]))
>>> ''.join(trans_table.get(c, c) for c in noob.lower() if c not in ' ')
'rznmlly'发布于 2017-02-05 04:25:08
下面是完成替换的一种功能方法:
s = "I am noob"
import string
letters = string.ascii_lowercase
# construct a dictionary mapping from a letter to its dual opposite starting from the end
# of the alphabet table
rep_dict = dict(zip(letters, letters[::-1]))
# use the dictionary to replace the letters
''.join(map(rep_dict.get, s.replace(" ", "").lower()))
# 'rznmlly'代码的问题在于您正在执行replace('a', 'z')....replace('z', 'a'),所以以前替换的所有字符都会被替换回来。
发布于 2017-02-05 04:25:21
您可以使用python的片来反转字符串:
>>> my_string = "abcdefghijqlmnopqrstuvwxyz"
>>> my_reversed_string = my_string[::-1]
>>> my_reversed_string
'zyxwvutsrqponmlqjihgfedcba'编辑:好的,问题是如何用反向字母表翻译字符串。有了这种问题,我想到的第一个问题是建立一本词典来做翻译:
>>> alphabet = "abcdefghijklmnopqrstuvwxyz"
>>> reversed_alphabet = alphabet[::-1] # zyxwvutsrqponmlkjihgfedcba
>>> my_dict = dict(zip(alphabet, reversed_alphabet))
>>> my_str = "i am noob"
>>> translated_str = ''.join(my_dict[c] for c in my_str.replace(' ', ''))
>>> translated_sentence
'rznmlly'https://stackoverflow.com/questions/42048510
复制相似问题