# count()統計字符串中特定單詞或短語出現次數(n = 3) strs = 'Good! Today is good day! Good job!' n = strs.lower().count("good") print(strs, "\ngood的個數:", n) print("輸出字符串前五個字符:", strs[0:5]) # 統計列表每個元素中指定單詞出現的個數(n = 2) n = 0 list = ['good day', 'bad', 'well', 'Good job'] for i in list: n += i.lower().count('good') print(list, "\ngood的個數:", n) # 統計列表中指定元素出現的個數(n = 1) n = 0 n = list.count('good day') print(list, "\ngood的個數:", n)
運行結果:
Good! Today is good day! Good job! good的個數: 3 輸出字符串前五個字符: Good! ['good day', 'bad', 'well', 'Good job'] good的個數: 2 ['good day', 'bad', 'well', 'Good job'] good的個數: 1