首页 > 解决方案 > 是否有函数或方法可以返回 Python 中列表或字符串中字符的位置值?

问题描述

那作业

 *Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name where "a" is 1, "b" is 2, "c" is 3, up to "z" being 26. For example, the name "Zelle" would have the value 26+5+12+12+5 = 60 (which happens to be a very auspicious number, by the way). Write a program that calculates the numeric value of a single name provided as input.*

这是我到目前为止所拥有的

def main():
    nameString = input("Enter your name to find its numeric value: ")
    letters = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    length = len(nameString)

for i in range(length):
    pos = nameString[i]
    value = letters.find(pos)
    newValue = value + 1
    print(newValue, end=" ")
    
main()

程序原样将采用输入的名称,通过循环的次数等于 nameString 的长度。我很难找到的是如何获得输入名称的字符之一的位置值。一旦我有了那个值,我需要给它加 1,因为字符串中的 A 从 0 开始,将它分配给一个变量,例如 newValue,然后再次循环,并将下一个字母的值添加到 newValue 等等然后打印出来。对于字符串或列表,我似乎找不到可以为我执行此操作的方法或函数。本书的这一章涵盖了字符串和列表,所以我应该使用其中的一个来找到解决方案。谢谢。

标签: pythonstringlist

解决方案


在 Python 中,所有“序列”(包括字符串)都有一个.index()方法来查找序列中值的位置。有关参与的字符串,请参阅:https ://docs.python.org/3/library/stdtypes.html#common-sequence-operations

列表和元组有一个等效的方法。


推荐阅读