2017-05-29 75 views
5

我想写一个二进制翻译器 - 与字符串作为输入和它的二进制表示作为输出。Python中的文本到二进制

而且我遇到了一些困难,我在变量中为每个字母编写了变量,但它们是变量,而不是字符串,所以我想从该变量的名称中获取输入并打印结果:

a = "01000001" 
b = "01000010" 
c = "01000011" 
d = "01000100" 
# all the way to z 


word = input("enter here: ") 
print (word) 

当我运行此我输入一个单词,它只是返回相同的字给我,但是当我写print(a)返回01000010,但我不能让它与输入工作。

有人可以告诉我我在哪里做错了什么?

+0

您正在打印的是您输入的“单词” – VK321

+0

您没有描述您的困难,也没有提出问题,这是一个问答网站,因此您的文本中某处的问号有助于找到您实际上是在问(例如,如果我切换到使用Java,这个神奇的工作,而不编码?) – Anthon

+1

如果我理解的很好,她想打印变量的值,将输入与变量的名称进行匹配,所以如果输入“a”字符,则不会得到结果,但是01000001,在我的答案中我认为它的工作原理 –

回答

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]) 
+0

非常感谢你,它终于成功了尝试几个小时谢谢 –

+0

@ErenBiçer我一直都很喜欢帮忙,不要忘记接受答案,用(✓) –

+3

尼斯破解,但不是一个好方法。使用[字典](https://docs.python。org/3/tutorial/datastructures.html#dictionaries)将是规范的方式。 – Matthias

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) 
+0

MarianD!Nice one,;)我真的很喜欢它+1 –

+0

@DamianLattenero - 谢谢(我的速度并不像你这么快)而你的解决方案记得我的东西我已经忘记了,并且更加尊重OP原始代码 – MarianD

+0

是的,并且很好的解释了 –