2014-11-25 47 views
-1

我的代碼:「預期的性格,但長度字符串#發現」加密程序無法正常工作

def Encryption(text): 
    for I in text: 
     string = "" 
     ASCII = ord(text) 
     Result = ASCII + Offset 
     if Result > 126: 
     Result -= 94 
     else: 
     Result = Result 
     ResultASCII = chr(Result) 
     string += ResultASCII 

對於我的第一塊GCSE課程,我們不得不做出的加密程序。我們必須做的最後一部分是實際加密您的消息的部分。我用這個代碼,但是它的錯誤出現:

TypeError: ord() expected a character, but string of length # found 

我如何得到它來檢測一個字符串,而不是僅僅一個角色?

回答

1

ord的說法是不是字符串,它必須是單個字符:

>>> ord('a') 
97 

,你可以嘗試這樣的事情遍歷字符串:

>>> a = 'hello' 
>>> [ ord(x) for x in a ] 
[104, 101, 108, 108, 111] 

替換此:

ASCII = ord(text) 

對此:

ASCII = ord(I) 
+0

我會用什麼代碼讀取整個字符串? – 2014-11-25 12:17:01

+0

你的問題並不清楚你想要訪問的內容 – Hackaholic 2014-11-25 12:20:19

+0

謝謝,但我會如何將它融入我的代碼?我嘗試在x中使用ASCII = ord(x),但它不起作用。 – 2014-11-25 12:21:47

0
ord: (c)                            │ 
│ ord(c) -> integer                         │                              
│ Return the integer ordinal of a one-character string.  

>>> ord('ab') 

Traceback (most recent call last): 
    File "<input>", line 1, in <module> 
TypeError: ord() expected a character, but string of length 2 found 

>>> ord('a') 
97