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)

“打印项目”声明是为了帮助我看看出了什么问题。我知道 total = 语句还不能工作,我正在修复它。基本上我要问的是,为什么“打印项目”打印数字 97?!

4

2 回答 2

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
于 2013-07-16T19:41:56.120 回答
0

在您的第二个语句中,您正在创建一个整数列表。让我们看一个例子:

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

如果要对列表中的项目求和,只需使用 sum。

>>> sum(a)
495

如果你想一次性完成所有事情:

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

希望这可以帮助。

于 2013-07-16T19:59:34.867 回答