Python Find the Position of a Substring in a String
In Python, you can usefind()method to find the position of a substring in a string. If the substring is found,find()the method returns the index of the first occurrence of the substring; if not found, it returns -1.
Example
# Define a string
text = "Hello, welcome to the world of Python."
# Find the position of the substring "welcome"
position = text.find("welcome")
# Output the result
print("The position of the substring is:", position)
text = "Hello, welcome to the world of Python."
# Find the position of the substring "welcome"
position = text.find("welcome")
# Output the result
print("The position of the substring is:", position)
Code analysis:
text = "Hello, welcome to the world of Python.": Define a stringtext。position = text.find("welcome"): Use thefind()method to find the substring"welcome"Intextin the string, and store the result in variableposition.print("子字符串的位置是:", position): Output the position of the substring.
Output result:
子字符串的位置是: 7
In this example, the substring"welcome"in the stringtexthas a starting position of index 7.
Python3 Examples