Python统计句子中D的数量触发AttributeError错误求助
解决统计句子中D数量函数的AttributeError问题
嘿,我看到你在这个统计句子里D(含大小写)数量的编程挑战里踩坑啦,咱们一步步来搞定这个问题~
错误原因分析
你代码里的核心问题出在这一行:
sentence = sentence.lower
lower()是Python字符串的实例方法,必须加上括号()才能调用它,将原字符串转换为全小写形式。你没加括号的话,sentence被赋值成了lower这个方法对象本身,而不是转小写后的字符串。后面调用count()方法时,方法对象没有count属性,自然就抛出了AttributeError: 'builtin_function_or_method' object has no attribute 'count'的错误。
修正后的代码
这里给你调整好的代码,同时保留了逻辑的清晰性:
def count_d(sentence): # 将句子转换为全小写,统一统计d和D的数量 lower_sentence = sentence.lower() # 统计小写d的出现次数 return lower_sentence.count("d")
测试验证
咱们用你给出的示例测试一下:
count_d("My friend Dylan got distracted in school.")➞ 4 ✅count_d("Debris was scattered all over the yard.")➞ 3 ✅count_d("The rodents hibernated in their den.")➞ 3 ✅
另外,如果你不需要调试用的print(sentence),可以直接去掉,不影响功能~
内容的提问来源于stack exchange,提问作者Mika Tan
相关产品推荐
相关产品推荐

