本文目录导读:

我来为您详细介绍Python中字符串精准查找的几种方法:
基础字符串方法
find() 方法
text = "Hello World, Hello Python"
index = text.find("Hello")
print(index) # 输出: 0
# 从指定位置开始查找
index = text.find("Hello", 5)
print(index) # 输出: 13
# 找不到返回-1
index = text.find("Java")
print(index) # 输出: -1
index() 方法
text = "Hello World, Hello Python"
try:
index = text.index("World")
print(index) # 输出: 6
except ValueError:
print("未找到匹配")
# 注意:index()找不到会抛出异常
# text.index("Java") # 会抛出ValueError
rfind() 和 rindex() - 从右向左查找
text = "Hello World, Hello Python"
print(text.rfind("Hello")) # 输出: 13 (最后一个Hello的位置)
print(text.rindex("Hello")) # 输出: 13
使用 in 运算符(推荐简单场景)
text = "Python是一种强大的编程语言"
keyword = "Python"
if keyword in text:
print(f"找到'{keyword}'")
else:
print(f"未找到'{keyword}'")
正则表达式匹配(最灵活)
精准匹配
import re
text = "我的邮箱是 test@example.com,备用邮箱 user@test.org"
# 查找匹配的邮箱
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
matches = re.findall(pattern, text)
print(matches) # 输出: ['test@example.com', 'user@test.org']
精确单词匹配
import re text = "Python编程 Python语言 python学习" # 匹配大小写敏感的精确单词 pattern = r'\bPython\b' matches = re.findall(pattern, text) print(matches) # 输出: ['Python', 'Python'] # 匹配不区分大小写 matches = re.findall(r'\bpython\b', text, re.IGNORECASE) print(matches) # 输出: ['Python', 'Python', 'python']
实用案例
案例1:敏感词过滤
def filter_sensitive_words(text, sensitive_words):
"""过滤敏感词"""
result = text
for word in sensitive_words:
if word in result:
# 用*替代敏感词
result = result.replace(word, '*' * len(word))
return result
text = "这个产品真的很垃圾,质量很差"
sensitive_words = ["垃圾", "很差"]
print(filter_sensitive_words(text, sensitive_words))
# 输出: 这个产品真的很**,质量**
案例2:提取URL链接
import re
def extract_urls(text):
"""提取文本中的URL"""
url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'
urls = re.findall(url_pattern, text)
return urls
text = "访问https://www.example.com了解更多,或http://test.com"
print(extract_urls(text))
# 输出: ['https://www.example.com', 'http://test.com']
案例3:验证输入格式
import re
def validate_phone(phone):
"""验证手机号格式"""
pattern = r'^1[3-9]\d{9}$'
return bool(re.match(pattern, phone))
def validate_email(email):
"""验证邮箱格式"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
# 测试
print(validate_phone("13800138000")) # True
print(validate_phone("12345678901")) # False
print(validate_email("test@example.com")) # True
案例4:提取特定模式的内容
import re
def extract_metrics(text):
"""提取文本中的数值指标"""
# 查找 "数字+单位" 模式
pattern = r'(\d+\.?\d*)\s*(公里|千米|米|厘米|毫米|千克|克|斤|公斤)'
metrics = re.findall(pattern, text)
return [(float(val), unit) for val, unit in metrics]
text = "距离车站500米,步行需要3分钟,体重65公斤"
print(extract_metrics(text))
# 输出: [(500.0, '米'), (65.0, '公斤')]
性能优化建议
import time
# 大量查找时的性能对比
text = "Hello " * 10000 + "Python"
# 方法1: in 运算符(最快)
start = time.time()
for _ in range(1000):
result = "Python" in text
print(f"in运算符: {time.time() - start:.4f}秒")
# 方法2: find()方法
start = time.time()
for _ in range(1000):
result = text.find("Python") != -1
print(f"find方法: {time.time() - start:.4f}秒")
# 方法3: 正则表达式(较慢但最灵活)
pattern = re.compile(r'\bPython\b')
start = time.time()
for _ in range(1000):
result = pattern.search(text) is not None
print(f"正则表达式: {time.time() - start:.4f}秒")
选择建议
- 简单查找:使用
in运算符 - 需要位置信息:使用
find()或index() - 复杂模式匹配:使用正则表达式
- 大量文本处理:预编译正则表达式
re.compile() - 精确单词匹配:
\b边界符配合正则
这些方法能覆盖大部分字符串精准查找的需求,根据具体场景选择合适的方法即可。