我有点被的挑战卡住了
目标是:"创建一个函数,计算一个句子中有多少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
这是我当前的代码:
def count_d(sentence):
print(sentence)
sentence = sentence.lower
substring = "d"
return sentence.count(substring)
当我运行它时,控制台会发送一条错误消息:
ERROR: Traceback:
in <module>
in count_d
AttributeError: 'builtin_function_or_method' object has no attribute 'count'
lower((,而不是仅lower。您希望方法返回值,而不是获取方法本身
如前所述,您需要调用方法,而不是获取方法本身。我想补充一点,你可能会连锁str
方法,即:
def count_d(sentence):
print(sentence)
substring = "d"
return sentence.lower().count(substring)
根据情况,这可能比每行执行一个操作更可读。