Tìm và thay thế

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data scientist

Tìm chuỗi con

  • Tìm chuỗi con chỉ định trong chuỗi mục tiêu.

my_string = "Where's Waldo?"
my_string.find("Waldo")
8
my_string.find("Wenda")
-1
Regular Expressions in Python

Tìm chuỗi con

  • Tìm chuỗi con chỉ định trong chuỗi mục tiêu.

my_string = "Where's Waldo?"
my_string.find("Waldo", 0, 6)
-1
Regular Expressions in Python

Hàm index

  • Tương tự .find(), tìm chuỗi con chỉ định trong chuỗi mục tiêu.

my_string = "Where's Waldo?"
my_string.index("Waldo")
8
my_string.index("Wenda")
File "<stdin>", line 1, in <module> 
ValueError: substring not found
Regular Expressions in Python

Hàm index

  • Tương tự .find(), tìm chuỗi con chỉ định trong chuỗi mục tiêu.

my_string = "Where's Waldo?"
try:
    my_string.index("Wenda")
except ValueError:
      print("Not found")
"Not found"
Regular Expressions in Python

Đếm số lần xuất hiện

  • Trả về số lần xuất hiện của chuỗi con chỉ định.

my_string = "How many fruits do you have in your fruit basket?"
my_string.count("fruit")
2
my_string.count("fruit", 0, 16)
1
Regular Expressions in Python

Thay thế chuỗi con

  • Thay thế chuỗi con bằng chuỗi mới.

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
Regular Expressions in Python

Tổng kết

  • Xử lý chuỗi:

    • Cắt lát và nối
    • Chỉnh chữ hoa/thường
    • Tách và ghép
    • Xóa ký tự ở đầu/cuối
    • Tìm chuỗi con
    • Đếm số lần xuất hiện
    • Thay thế chuỗi con
Regular Expressions in Python

Ayo berlatih!

Regular Expressions in Python

Preparing Video For Download...