Python Find the Position of a Substring in a String
In Python, you can use the find() method to find the position of a substring in a string. If the substring is found, thefind() method returns the index of its first occurrence; 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 result
(
"The position of the substring is:"
,
position
)
Code analysis:
text = "Hello, welcome to the world of Python.": define a stringtext。position = text.find("welcome"): When usingfind()The method finds the substring"welcome"intextand stores the result in the variablepositionit.print("子字符串的位置是:", position): Print the position of the substring.
Output result:
子字符串的位置是: 7
In this example, the substring "welcome" in the string text has a starting position of index 7 in .
Python3 Examples