欢迎访问宙启技术站
智能推送

如何使用Python函数来查找字符串中的子串?

发布时间:2023-07-01 09:08:39

在Python中,可以使用内置函数和字符串方法来查找字符串中的子串。下面是一些常用的方法:

1. 使用内置函数find()

str = "Hello, World!"
substring = "lo"
index = str.find(substring)
print(index)  # 输出4

find()函数在字符串中搜索指定的子串,如果找到则返回子串 次出现的索引,如果未找到则返回-1。

2. 使用内置函数index()

str = "Hello, World!"
substring = "lo"
index = str.index(substring)
print(index)  # 输出4

index()函数与find()类似,但如果未找到子串,则会引发一个ValueError异常。

3. 使用字符串方法startswith()和endswith()

str = "Hello, World!"
substring = "Hello"
starts_with = str.startswith(substring)
ends_with = str.endswith(substring)
print(starts_with)  # 输出True
print(ends_with)  # 输出False

startswith()和endswith()函数用于检查字符串是否以指定的子串开始或结束,返回布尔值。

4. 使用正则表达式模块re

import re

str = "Hello, World!"
pattern = r"lo"
matches = re.findall(pattern, str)
print(matches)  # 输出['lo']

re模块提供了强大的正则表达式功能,可以通过findall()函数找到字符串中匹配指定模式的所有子串。

5. 使用字符串方法count()

str = "Hello, World!"
substring = "l"
count = str.count(substring)
print(count)  # 输出3

count()函数返回子串在字符串中出现的次数。

6. 使用字符串方法split()

str = "Hello, World!"
substring = " "
parts = str.split(substring)
print(parts)  # 输出['Hello,', 'World!']

split()函数将字符串分割为子串列表,根据指定的分隔符进行分割。

以上是几种常见的方法,根据具体需求选择合适的方法来查找字符串中的子串。