How can you retrieve the index of a substring in Python?

In Python, you can use the find() method or regular expressions to locate the index of a substring. Below are examples of both methods:

Option 1:
Method 1: Utilize the find() method.

string = "Hello, World!"
substring = "World"

index = string.find(substring)
if index != -1:
    print("子字符串的序号是:", index)
else:
    print("子字符串不存在")

Option 1: Method 2: Regular expression usage

import re

string = "Hello, World!"
substring = "World"

pattern = re.compile(substring)
match = pattern.search(string)
if match:
    print("子字符串的序号是:", match.start())
else:
    print("子字符串不存在")

Regardless of the method used, the index of the substring can be obtained. It is important to note that the find() method returns the position of the first occurrence of the substring, and -1 if the substring does not exist; whereas the search() method in regular expressions returns the first match result, and the start() method can be used to obtain the starting position of the match.

bannerAds