1. 使用字符串的 find() 方法Python的字符串对象提供了一个非常实用的 find() 方法,它可以用来查找子串在字符串中的位置。如果找到了子串,find() 会返回子串的起始索引;如果没有...
find() 方法Python的字符串对象提供了一个非常实用的 find() 方法,它可以用来查找子串在字符串中的位置。如果找到了子串,find() 会返回子串的起始索引;如果没有找到,则返回 -1。
text = "Hello, world!"
position = text.find("world")
if position != -1: print(f"子串 'world' 在文本中的位置是:{position}")
else: print("子串 'world' 未找到。")find(sub[, start[, end]]):查找子串 sub 在字符串中的位置。sub:要查找的子串。start:开始搜索的索引位置。end:结束搜索的索引位置。index() 方法index() 方法与 find() 类似,也是用来查找子串位置的,但它会抛出一个异常(ValueError)如果子串不存在。
text = "Hello, world!"
try: position = text.index("world") print(f"子串 'world' 在文本中的位置是:{position}")
except ValueError: print("子串 'world' 未找到。")index(sub[, start[, end]]):与 find() 方法类似,但会抛出异常。count() 方法count() 方法用于计算子串在字符串中出现的次数。
text = "Hello, world! Hello, Python!"
count = text.count("Hello")
print(f"子串 'Hello' 出现了 {count} 次。")count(sub[, start[, end]]):计算子串 sub 在字符串中出现的次数。sub:要计数的子串。start:开始计数的索引位置。end:结束计数的索引位置。正则表达式是强大的文本匹配工具,Python的 re 模块提供了丰富的正则表达式功能。
import re
text = "Hello, world! Hello, Python!"
pattern = re.compile(r"Hello")
matches = pattern.findall(text)
print(f"匹配到的子串有:{matches}")re.compile(pattern):编译正则表达式模式。findall(pattern):查找所有匹配的子串。split() 方法split() 方法可以根据指定的分隔符将字符串分割成子串列表。
text = "Hello, world! Hello, Python!"
split_text = text.split(", ")
print(f"分割后的子串列表:{split_text}")split(sep=None[, maxsplit=-1]):根据分隔符 sep 将字符串分割成子串列表。sep:分隔符。maxsplit:最大分割次数。通过以上五大绝招,你可以轻松地掌握Python中的文本匹配技巧。无论是查找子串、计数子串出现次数,还是进行复杂的正则表达式匹配,这些方法都能派上用场。