了解如何使用Python字符串統計子串出現次數

利用 Python String “字符串統計子串出現次數”為主題

Python 是一種腳本語言,它的字串操作功能十分強大,可以輕鬆的處理字串的統計子串出現次數的問題。本文將介紹如何使用 Python 來統計字串中子串出現的次數。

首先,我們要先建立一個字串,作為示範:

str = "Python is a great language. I love Python"

接著,我們可以使用 count() 方法來統計子串出現的次數:

# 統計字串中 "Python" 出現的次數
print(str.count("Python"))

執行結果為:

2

可以看到,字串中 “Python” 出現了兩次,因此執行結果為 2。

另外,我們也可以使用 find() 方法來統計子串出現的次數:

# 統計字串中 "Python" 出現的次數
count = 0
pos = 0
while True:
    pos = str.find("Python", pos)
    if pos == -1:
        break
    count += 1
    pos += 1
print(count)

執行結果為:

2

可以看到,字串中 “Python” 出現了兩次,因此執行結果為 2。

總結,使用 Python 來統計字串中子串出現的次數,可以使用 count()find() 方法,它們都可以得到正確的結果。

發佈留言