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

如何使用Python函数在字符串中查找指定的子串并返回该子串的位置?

发布时间:2023-07-04 11:18:25

要在字符串中查找指定的子串并返回其位置,可以使用Python中的函数 find()index()

1. 使用 find() 函数:

   def find_substring(string, substring):
       index = string.find(substring)
       if index != -1:
           return index
       else:
           return "Substring not found."
   

在上述代码中,find_substring() 函数接受两个参数:stringsubstringfind() 函数用于在 string 中查找 substring。如果找到则返回子串的首个字符的索引,否则返回-1。如果返回值不是-1,则返回该索引;否则返回 "Substring not found."。

使用示例:

   input_string = "Hello, world!"
   target_substring = "world"
   
   result = find_substring(input_string, target_substring)
   print(result) # 输出: 7
   

2. 使用 index() 函数:

   def find_substring(string, substring):
       try:
           index = string.index(substring)
           return index
       except ValueError:
           return "Substring not found."
   

上述代码中的 find_substring() 函数也接收两个参数:stringsubstring。使用 index() 函数在 string 中查找 substring。如果找到则返回子串的首个字符的索引,如果未找到则引发 ValueError 异常,可以通过 try-except 语句捕获并返回 "Substring not found."。

使用示例:

   input_string = "Hello, world!"
   target_substring = "world"
   
   result = find_substring(input_string, target_substring)
   print(result) # 输出: 7
   

这些方法可用于在字符串中快速查找子串,并返回其位置或指示未找到的消息。