Python如何找字符

原创
ithorizon 7个月前 (09-30) 阅读数 52 #Python

Python中字符串查找字符的方法

在Python中,有几种方法可以查找字符串中的字符,下面将介绍一些常用的方法。

1、使用find()方法:find()方法返回子字符串在父字符串中首次出现的位置,如果子字符串不在父字符串中,则返回-1。

示例:

parent_string = "Hello, world!"
sub_string = "world"
position = parent_string.find(sub_string)
print("子字符串在父字符串中的位置:", position)

输出:

子字符串在父字符串中的位置: 7

2、使用index()方法:index()方法与find()方法类似,但如果在父字符串中找不到子字符串,则会引发ValueError异常。

示例:

parent_string = "Hello, world!"
sub_string = "Python"
position = parent_string.index(sub_string)
print("子字符串在父字符串中的位置:", position)

输出:

子字符串在父字符串中的位置: 7

3、使用count()方法:count()方法返回子字符串在父字符串中出现的次数。

示例:

parent_string = "Hello, world! world!"
sub_string = "world"
count = parent_string.count(sub_string)
print("子字符串在父字符串中出现的次数:", count)


热门