2013-07-16 33 views
1

我正在爲一個挑戰給我一個程序:取一個字符串,找到每個字母的ASCII值,並將這些數字相加並返回最終值。我有這麼多:可變返回奇怪號碼

def AddAsciiList(string): 
    ascii = [ord(c) for c in string] 
    for item in ascii: 
     print item 
     total = ascii[i-1] + ascii[i] 
    return total 
string = raw_input("Enter String:") 
AddAsciiList(string) 

「打印項目」聲明是爲了幫助我看看出了什麼問題。我知道總數=聲明還沒有起作用,我正在修復它。基本上我問的是,爲什麼「打印項目」打印數字97?!

+1

'ord('a')== 97'。而且你必須在你的字符串中有一個「a」。 –

+0

你似乎沒有在任何地方定義「我」......這是否意味着「項目」? – Ben

+0

是的,我正在改變它。 –

回答

4

這是因爲ord()返回數字的ASCII碼,並且ascii列表包含代碼。看例子 -

>>> testString = "test" 
>>> testList = [ord(elem) for elem in testString] # testList = map(ord, testString) is another way. 
>>> testList 
[116, 101, 115, 116] 

而且,當你迭代列表,你會得到打印出來的整數值。

它打印97,因爲你必須在你的輸入字符串的'a',作爲

>>> chr(97) 
'a' 

見什麼help功能不得不說 -

>>> help(ord) 
Help on built-in function ord in module __builtin__: 

ord(...) 
    ord(c) -> integer 

    Return the integer ordinal of a one-character string. 

如果你想添加的所有字符串中的字符的ASCII碼,請執行

>>> sum(map(ord, testString)) 
448 

>>> sum(ord(elem) for elem in testString) 
448 
0

在你的第二份聲明,你要創建一個整數列表。讓我們來看一個例子:

>>> s = 'abcde' 
>>> a = [ord(c) for c in s] 
>>> a 
[97, 98, 99, 100, 101] 
>>> 

如果你想總結列表中的項目,只需使用sum。

>>> sum(a) 
495 

如果你想要做整個事情在一個膨脹foop:

>>> total = sum(ord(c) for c in s) 
>>> total 
495 

希望這有助於。