变回怪异麻木

2024-10-02 12:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个给我的挑战做一个程序:取一个字符串,找到每个字母的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=语句还不起作用,我正在着手解决它。基本上我想问的是,为什么“print item”要打印97号?!你知道吗


Tags: 字符串in程序forstringreturndef字母
2条回答

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

>>> 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

希望这有帮助。你知道吗

这是因为^{}返回数字的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

相关问题 更多 >

    热门问题