Python 字符串 find() 方法详解:查找子字符串位置
问题:
以下 Python 程序的输出结果是什么?
str1 = 'Runoob example....wow!!!'
str2 = 'exam'
print(str1.find(str2, 5))
A. 10
B. 7
C. 2
D. -1
答案:B. 7
解释:
find() 方法用于在字符串中查找子字符串的第一次出现。它有两个参数:
- 要查找的子字符串
- 开始搜索的起始索引(可选,默认为 0)
find() 方法返回子字符串在字符串中第一次出现的索引。如果未找到子字符串,则返回 -1。
在本例中,我们从索引 5 开始在字符串 str1 中查找子字符串 str2 ('exam')。子字符串 'exam' 在 str1 中的索引 7 处第一次出现。
以下是代码执行步骤的分解:
str1.find(str2, 5):从索引 5 开始在字符串 'Runoob example....wow!!!' 中查找子字符串 'exam'。find()方法返回子字符串 'exam' 在str1中第一次出现的索引,即 7。print(str1.find(str2, 5)):打印结果 7。
因此,该程序的输出结果为 7。
原文地址: https://www.cveoy.top/t/topic/f09Y 著作权归作者所有。请勿转载和采集!