我正在尝试编写二进制翻译器 - 将字符串作为输入,将二进制表示作为输出。
我遇到了一些困难,我在变量中写了每个字母的翻译,但它们是变量,而不是字符串,所以我想从变量的名称中获取输入的输入并输出结果:
a = "01000001"
b = "01000010"
c = "01000011"
d = "01000100"
# all the way to z
word = input("enter here: ")
print (word)
当我运行这个时,我输入一个单词,它只是向我返回相同的单词,但是当我写print(a)
时,它返回01000010
但我无法使用输入。< / p>
有人可以告诉我我做错了什么吗?
答案 0 :(得分:5)
根据用户的评论,对于这些案例使用字典编程是一种更好的做法,您只需要填写字典letterToBin
,如示例中所示
这是一本字典,意思是它有一把钥匙和一个价值,比如一部手机,你有钥匙作为名字(你的母亲)和价值(他的手机):
letterToBin = {}
letterToBin = {
"a" : "01000001", #Here, the key is the "a" letter, and the value, his bin transformation, the 01000001
"b" : "01000010",
"c" : "01000011",
"d" : "01000100"
#so you need to add all the other keys you need, for example the "e"
"e" : "01000101" #for example
}
binToLetter = {} # here I create a second dictionary, and it invert the values of the first, it meas, now the keys will be the bins, and the value the latters
binToLetter = dict(zip(letterToBin.values(), letterToBin.keys())) #this code do the magic, you must understand, that only needs to feel the first dictionary, and for free, you will have the second dictionary
wordOrBin = input("enter here: ")
if wordOrBin in letterToBin:
print(letterToBin[wordOrBin]) #here I has if you write a latter (a) or a bin(11001101) and it choose where to look the correct value
else:
print(binToLetter[wordOrBin])
答案 1 :(得分:3)
可能更正确的解决方案是使用字典而不是字母名称作为变量名称:
transDict = {
"a": "01100001",
"b": "01100010",
"c": "01100011",
"d": "01100100",
# etc., etc.
}
text = input( "Enter your message: " )
result = "".join( [transDict[letter] for letter in text] )
print(result)
(我还更正了ASCII
代码 - 您的代码是大写字母。)
解释
(最长的陈述):
“使用""
作为分隔符(即no delimiter
)加入 已翻译字母列表中的所有项目其他来自text
“。
所以结果与使用这些命令的结果相同:
listOfCodes = [] # Starting with an empty list
for letter in text: # For letter by letter in text perform 2 actions:
code = transDict[letter] # - translate the letter
listOfCodes.append( code ) # - append the translation to the list
result = "".join( listOfCodes ) # Then join items of the list without a delimiter
# (as "" is an empty string) (" " would be nicer)