我想知道如何检查某些字母的字符串以便为它们添加值,以便我可以将它们添加起来,然后将总数返回给用户。
我该怎么做呢?
答案 0 :(得分:2)
a_string = "abcde"
letters = ["a", "e", "i", "o", "u"]
for x in a_string:
if(x in letters):
print(x+" is in "+a_string)
从这里你可以使用字典将“x”映射到一个点值。
答案 1 :(得分:0)
这可以使用字典和循环轻松完成。
# Dictionary matching letters to values
letter_val = {'a': 1,
'b': 2,
'c': 3,
'd': 4
}
def myFunction(s):
"""Function takes a string and checks each character
against the dictionary values. If letter is in then
add value to result"""
res = 0
for char in s:
if char in letter_val:
res += letter_val[char]
return res
答案 2 :(得分:0)
如果您不想为字母指定特定值,可以使用Unicode整数并扣除Unicode起始值以获得1到24(a-z):
>>> a = 'aBcDefghijklmnopqrstuvwXyZ'
>>> tot=0
>>> for i in a:
... tot+=int(ord(i.lower()))-96
...
>>> tot
351
ord()
返回字符的Unicode值,其中" a" = 97而i.lower()
将所有字母转换为小写字母
要使用大写字母运行,请使用i.upper()
代替并扣除64,其中Unicode值为" A"是65