有人能解释一下为什么我下面的特殊复杂代码不起作用吗?我尝试在谷歌上搜索,但找不到我理解的答案。显示错误,表明我的 count() 显然只允许“3 个参数”。所以想知道是否有一种简单的方法可以解决这个问题。我知道其中有一个“string.count”函数,但我似乎无法让它们工作。
非常感谢您花时间提供帮助!
print("Welcome to the Love Calculator")
name1 = input("What is your name?")
name2 = input("What is their name?")
name_1_lower_case = name1.lower()
name_2_lower_case = name2.lower()
both_names = name_1_lower_case + name_2_lower_case
calculate_true = both_names.count("t", "r", "u", "e")
calculate_love = both_names.count("l", "o", "v", "e")
total_score = str(calculate_true) + str(calculate_love)
print(total_score)
将代码更改为:
print("Welcome to the Love Calculator")
name1 = input("What is your name?")
name2 = input("What is their name?")
name_1_lower_case = name1.lower()
name_2_lower_case = name2.lower()
both_names = name_1_lower_case + name_2_lower_case
count_t = both_names.count("t")
count_r = both_names.count("r")
count_u = both_names.count("u")
count_e = both_names.count("e")
calculate_true = count_t + count_r + count_u + count_e
count_l = both_names.count("l")
count_o = both_names.count("o")
count_v = both_names.count("v")
calculate_love = count_l + count_o + count_v + count_e
total_score = str(calculate_true) + str(calculate_love)
print(total_score)
count 方法采用子字符串(或单个字符)来查找,以及可选的要搜索的索引的开头和/或结尾。您正在尝试向其发送大量不同的子字符串来查找。
您可能可以完成您想要的事情
total_score = sum( [ both_names.count( c ) for c in "true" + "love" ] )