答案:Python中查找子字符串最简洁的方法是使用in操作符,它返回布尔值表示是否存在;若需获取位置可用find()或index(),前者未找到时返回-1,后者抛出异常;统计次数用count();复杂模式匹配则推荐re模块。

Python在字符串中查找子字符串的方法非常丰富且灵活,从简单的存在性判断到复杂模式匹配,你总能找到一个趁手的工具。核心方法包括利用
in
find()
index()
count()
re
说实话,在Python里处理字符串查找,我个人觉得是件挺舒服的事,因为它提供了太多直观的API。我们来一步步看看这些方法,以及我通常会怎么选择它们。
首先,最基础也是最常用的,就是in
main_string = "Hello, world! This is a test." sub_string = "world" sub_string_not_found = "python" print(sub_string in main_string) # 输出: True print(sub_string_not_found in main_string) # 输出: False
它不给你位置,也不告诉你出现了多少次,就一个“是”或“否”,但很多时候,这已经足够了。
立即学习“Python免费学习笔记(深入)”;
接下来,如果你不仅想知道“有没有”,还想知道“在哪里”,那么str.find()
-1
main_string = "Python programming is fun. Python is versatile."
sub_string = "Python"
sub_string_not_found = "Java"
print(main_string.find(sub_string)) # 输出: 0 (第一个'P'的索引)
print(main_string.find("is")) # 输出: 19 (第一个'is'的索引)
print(main_string.find(sub_string_not_found)) # 输出: -1
# 你还可以指定搜索的起始和结束位置
print(main_string.find("Python", 1)) # 从索引1开始找,找到第二个'Python',输出: 27
print(main_string.find("is", 20, 30)) # 在索引20到29之间找'is',输出: 22与
find()
str.index()
ValueError
index()
main_string = "Learning Python is great."
sub_string = "Python"
sub_string_not_found = "Ruby"
print(main_string.index(sub_string)) # 输出: 9
try:
print(main_string.index(sub_string_not_found))
except ValueError as e:
print(f"出错了: {e}") # 输出: 出错了: substring not found有时候,我们不想要第一次出现的位置,而是想知道最后一次出现的位置。这时候,str.rfind()
str.rindex()
find()
index()
main_string = "banana is a yellow fruit, banana is tasty."
print(main_string.rfind("banana")) # 输出: 29
print(main_string.rindex("is")) # 输出: 26如果你想知道一个子字符串出现了多少次,str.count()
main_string = "abracadabra, abracadabra!"
print(main_string.count("abra")) # 输出: 2
print(main_string.count("a")) # 输出: 8最后,当你的查找需求变得复杂,比如要匹配某种模式(例如,所有以数字开头的单词,或者特定的日期格式),那么Python的re
import re
text = "My phone number is 123-456-7890. Call me at 987-654-3210."
# 查找所有电话号码模式
phone_numbers = re.findall(r'\d{3}-\d{3}-\d{4}', text)
print(phone_numbers) # 输出: ['123-456-7890', '987-654-3210']
# 查找第一个匹配项
match = re.search(r'phone number is (\d{3}-\d{3}-\d{4})', text)
if match:
print(f"第一个电话号码是: {match.group(1)}") # 输出: 第一个电话号码是: 123-456-7890re
re.search()
re.findall()
re.finditer()
re.sub()
要判断一个子字符串是否存在于另一个字符串中,最简洁、最Pythonic的方法无疑是使用in
True
False
sentence = "The quick brown fox jumps over the lazy dog."
# 检查是否存在 "fox"
if "fox" in sentence:
print("找到了狐狸!") # 输出: 找到了狐狸!
# 检查是否存在 "cat"
if "cat" not in sentence:
print("没有找到猫。") # 输出: 没有找到猫。我个人在日常编码中,如果仅仅是想知道某个元素是否在集合(包括字符串、列表、元组等)中,几乎都会下意识地用
in
in
find()
index()
要获取子字符串在主字符串中的具体位置,Python主要提供了
str.find()
str.index()
str.find(sub[, start[, end]])
sub
-1
-1
text = "Python is a great language, Python is widely used."
position1 = text.find("great")
position2 = text.find("Java")
position3 = text.find("Python", 10) # 从索引10开始查找
print(f"'great' 的位置: {position1}") # 输出: 'great' 的位置: 12
print(f"'Java' 的位置: {position2}") # 输出: 'Java' 的位置: -1
print(f"从索引10开始找 'Python' 的位置: {position3}") # 输出: 从索引10开始找 'Python' 的位置: 25str.index(sub[, start[, end]])
sub
ValueError
try-except
text = "Data science with Python is fascinating."
position_python = text.index("Python")
print(f"'Python' 的位置: {position_python}") # 输出: 'Python' 的位置: 17
try:
position_r = text.index("R")
print(f"'R' 的位置: {position_r}")
except ValueError as e:
print(f"捕获到错误: {e}") # 输出: 捕获到错误: substring not found何时选择?
find()
-1
find()
index()
index()
index()
这两个方法都支持可选的
start
end
当你的需求从简单的“有没有”或“在哪里”升级到“有多少个”或“符合某种模式的所有匹配项”,Python的
str.count()
re
1. 统计子字符串的出现次数:str.count()
如果你只是想知道一个特定的子字符串在主字符串中出现了多少次,
str.count()
document = "Apple is a fruit. I like apple. Apple pie is delicious."
print(f"'Apple' 出现了 {document.count('Apple')} 次。") # 输出: 'Apple' 出现了 2 次。
print(f"'apple' 出现了 {document.count('apple')} 次。") # 输出: 'apple' 出现了 1 次。
print(f"'is' 出现了 {document.count('is')} 次。") # 输出: 'is' 出现了 3 次。
# 注意:count方法是区分大小写的。count()
start
end
long_text = "one two one three one four"
print(long_text.count("one", 5, 20)) # 在索引5到19之间查找'one',输出: 1 (只找到'one three'中的那个'one')2. 查找更复杂的模式或所有匹配项:re
当你的查找需求超越了简单的字面量匹配,比如你需要:
这时候,就该请出
re
re.findall(pattern, string, flags=0)
这是我最常用的一种模式,它会找到字符串中所有与
pattern
import re
log_data = "Error: File not found (code 404). Warning: Low disk space. Error: Network timeout (code 500)."
# 查找所有错误代码
error_codes = re.findall(r'code (\d{3})', log_data)
print(f"所有错误代码: {error_codes}") # 输出: 所有错误代码: ['404', '500']
# 查找所有单词(忽略大小写)
words = re.findall(r'\b\w+\b', log_data.lower())
print(f"所有单词: {words}") # 输出: 所有单词: ['error', 'file', 'not', 'found', 'code', '404', 'warning', 'low', 'disk', 'space', 'error', 'network', 'timeout', 'code', '500']re.search(pattern, string, flags=0)
如果你只需要找到第一个匹配项,
re.search()
Match object
None
Match object
text = "The price is $12.99, but on sale for $9.50."
match = re.search(r'\$\d+\.\d{2}', text) # 查找第一个货币金额
if match:
print(f"第一个金额: {match.group(0)}") # group(0)是整个匹配到的字符串,输出: 第一个金额: $12.99
print(f"起始位置: {match.start()}, 结束位置: {match.end()}") # 输出: 起始位置: 13, 结束位置: 19
match_none = re.search(r'€\d+', text) # 查找欧元符号,不存在
print(f"查找欧元金额: {match_none}") # 输出: 查找欧元金额: Nonere.finditer(pattern, string, flags=0)
这个方法返回一个迭代器,其中包含了所有匹配项的
Match object
finditer()
findall()
import re
code_snippet = "def func_a(): pass\nclass MyClass:\n def method_b(): pass\ndef func_c(): pass"
# 查找所有函数或方法的定义
for match in re.finditer(r'(def|class)\s+(\w+)\s*\(.*?\):', code_snippet):
print(f"类型: {match.group(1)}, 名称: {match.group(2)}")
# 输出:
# 类型: def, 名称: func_a
# 类型: class, 名称: MyClass
# 类型: def, 名称: method_b
# 类型: def, 名称: func_c正则表达式的标志 (Flags):
re
re.IGNORECASE
re.I
re.MULTILINE
re.M
^
$
re.DOTALL
re.S
.
text_case_insensitive = "Python is great. python is powerful."
matches = re.findall(r'python', text_case_insensitive, re.IGNORECASE)
print(f"忽略大小写查找 'python': {matches}") # 输出: 忽略大小写查找 'python': ['Python', 'python']总而言之,对于简单的计数,
str.count()
re
以上就是python怎么在字符串中查找子字符串_python字符串查找方法详解的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号