查找与替换

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 中的正则表达式

¡Vamos a practicar!

Python 中的正则表达式

Preparing Video For Download...