尋找與取代

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data scientist

尋找子字串

  • 在目標字串中尋找指定子字串。

my_string = "Where's Waldo?"
my_string.find("Waldo")
8
my_string.find("Wenda")
-1
Python 中的正規表示法

尋找子字串

  • 在目標字串中尋找指定子字串。

my_string = "Where's Waldo?"
my_string.find("Waldo", 0, 6)
-1
Python 中的正規表示法

index 函式

  • 類似 .find(),在目標字串中尋找指定子字串。

my_string = "Where's Waldo?"
my_string.index("Waldo")
8
my_string.index("Wenda")
File "<stdin>", line 1, in <module> 
ValueError: substring not found
Python 中的正規表示法

index 函式

  • 類似 .find(),在目標字串中尋找指定子字串。

my_string = "Where's Waldo?"
try:
    my_string.index("Wenda")
except ValueError:
      print("Not found")
"Not found"
Python 中的正規表示法

計算出現次數

  • 回傳指定子字串出現的次數。

my_string = "How many fruits do you have in your fruit basket?"
my_string.count("fruit")
2
my_string.count("fruit", 0, 16)
1
Python 中的正規表示法

取代子字串

  • 以新子字串取代原子字串的出現處。

my_string = "The red house is between the blue house and the old house"
print(my_string.replace("house", "car"))
The red car is between the blue car and the old car
print(my_string.replace("house", "car", 2))
The red car is between the blue car and the old house
Python 中的正規表示法

重點回顧

  • 字串處理

    • 切片與串接
    • 大小寫調整
    • 分割與合併
    • 去除開頭與結尾字元
    • 尋找子字串
    • 計算出現次數
    • 取代子字串
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...