検索と置換

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...