【Python 字串處理 #6】python find 使用方法,在字串中找尋子字串 string find python

前言

我們會需要在字串中尋找特定子字串的功能,
這裡我們使用 python 的 find 函數來幫助我們實現找子字串的功能

範例程式碼

因為 find 功能相對單純,我們先直接來看例子,
讀者可以自己觀察判斷看看能不能理解!

可先觀察結果,下面再來慢慢說明

>>> main_str = "test_data"
>>> print(main_str.find('test'))
0
>>> print(main_str.find('data'))
5
>>> print(main_str.find('hello'))
-1

str.find(’test’) 會回傳找到的子字串所在的 「index 起始位置 (從 0 開始)」
如果沒有會回傳 -1

就是這樣,非常簡單XD

應用

其實最重要的還是如何把上面的內容應用到自己的程式上,
例如以下我舉一個我自己最常用的例子:

  • 如果找到「特定字串」,做 A 事情,如果沒有找到,做 B 事情。
main_str = "test_data"
str_founded = main_str.find('test')
    if(str_founded == -1): # not found
        print("DO if NOT found.")
    else: # found
        print("DO if found.")

Reference