我该如何编写一个python向用户询问句子并打印句子中“ the”使用了多少时间。 这是我尝试过的代码
string1=str(input("Enter a sentence"))
splitstring= string1.split()
list1=[]
for word in splitstring:
if word== 'the':
list1.append(word)
lengthstring= len(list1)
print("The number of times the word the occurs in the string is ", lengthstring)
答案 0 :(得分:1)
您的代码有效,但是您可以像这样用count()计算列表中元素出现的次数:
string1 = input("Enter a sentence: ")
splitstring = string1.split()
print("The number of times the word the occurs in the string is ", splitstring.count('the'))