该程序根据用户输入创建列表。然后,用户输入一个子字符串以在列表中进行搜索。我想计算子串出现在列表中的实例。例如:input_list = [python treeree 3 free]。 search_str ='ree'。总数应为4。
我已经尝试过使用sum()函数来获得正确的结果,但是我需要解析单词列表以进行作业分配。
total = 0
input_list = input('Type a list of words separated by a space: ')
search_str = str(input('Type a string to search for: '))
input_list = input_list.lower().split()
for x in input_list:
if search_str in x:
total = total + 1
print(search_str,": ",total)
代码运行,但是,不计算字符串出现的总数(即4),而是仅计算出现字符串的总数(即3)。
如果允许使用count
,则可以替换:
if search_str in x:
total = total + 1
with:
total += x.count(search_str)
它将在search_str
中计算x
的所有实例,为您提供预期的结果。