2016-10-02 156 views
0

我需要從我獲得的數字值到字符的部分拼出一個單詞不起作用,它說我需要爲最後一部分使用整數?將數值轉換爲ASCII字符?

接受串

print "This program reduces and decodes a coded message and determines if it is a palindrome" 
string=(str(raw_input("The code is:"))) 

改變它爲小寫

string_lowercase=string.lower() 
print "lower case string is:", string_lowercase 

條特殊字符

specialcharacters="1234567890~`[email protected]#$%^&*()_-+={[}]|\:;'<,>.?/" 

for char in specialcharacters: 
    string_lowercase=string_lowercase.replace(char,"") 

print "With the specials stripped out the string is:", string_lowercase 

輸入偏移

offset=(int(raw_input("enter offset:"))) 

轉換文本的ASCII碼的

result=[] 
for i in string_lowercase: 
    code=ord(i) 
    result.append([code-offset]) 

轉換爲ASCII碼文本

text=''.join(chr(i) for i in result) 
print "The decoded string is:", text.format(chr(result)) 
+2

你所說的「不工作」的意思?另外,假設你之前使用了'import string',那麼對於「strip special characters」部分,我會去'string_lowercase = [x for string_lowercase in string.ascii_letters]'''。最後,不要命名你的變量'string'。 – Efferalgan

+0

**「零件不工作」**。哪一部分是這樣的,你爲什麼還要向我們展示那麼多其他部分,讓我對這個問題的位置感到困惑?更好地展示並詢問第一部分做錯了什麼。 (後面的部分可能只會做錯誤的事情,因爲他們已經得到錯誤的數據。) –

回答

0

看起來你有一個列表的列表,而不是整數的列表,當你調用result.append([code-offset])。這意味着稍後當您撥打chr(i) for i in result時,您將通過一個列表而不是int到chr()

嘗試將其更改爲result.append(code-offset)

其他小建議:

  • raw_input已經爲您提供了一個字符串,所以沒有必要明確地投它。
  • 你去除特殊字符可以更有效地寫爲:

    special_characters = '1234567890~`[email protected]#$%^&*()_-+={[}]|\:;'<,>.?/' 
    string_lowercase = ''.join(c for c in string_lowercase if string not in special_characters) 
    

    這可以讓你只需要通過一次string_lowercase而不是每個字符在special_characters進行迭代。

0

當您只接受整數時,您將一個列表傳遞給chr。試試result.append(code-offset)[code-offset]是一個單項列表。

代替

具體:

result=[] 
for i in string_lowercase: 
    code=ord(i) 
    result.append([code-offset]) 

使用:

result=[] 
for i in string_lowercase: 
    code=ord(i) 
    result.append(code-offset) 

如果你瞭解列表理解,這個工程太:result = [ord(i)-offset for i in string_lowercase]

+0

告訴我,如果別的東西不起作用。 – 2016-10-02 20:29:51

0

雖然做.append()列出,使用code-offset代替[code-offset]。如後面所述,您將該值存儲爲(一個ASCII的)列表,而不是直接存儲ASCII值。

因此你的代碼應該是:

result = [] 
for i in string_lowercase: 
    code = ord(i) 
    result.append(code-offset) 

然而,你可能簡化了這個代碼:

result = [ord(ch)-offset for ch in string_lowercase] 

你甚至可以進一步簡化代碼。一條線得到解碼的字符串將是:

decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase) 

隨偏移距爲2:

>>> string_lowercase = 'abcdefghijklmnopqrstuvwxyz' 
>>> offset = 2 
>>> decoded_string = ''.join(chr(ord(ch)-offset) for ch in string_lowercase) 
>>> decoded_string 
'_`abcdefghijklmnopqrstuvwx'