python之count()函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()函数的主要内容,如果未能解决你的问题,请参考以下文章

Python之函数初识

Python之函数初识

python之count()函数

Python之函数定义函数以及传参

Python之如何优雅的重试

python之定义函数