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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM