首页 > 代码库 > python之count()函数

python之count()函数

# 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

  

python之count()函数