2017-05-29 73 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

是的,並且很好的解釋了 –