Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Position of a Substring in a String

Python Find the Position of a Substring in a String

Document Object Reference Manual Python3 Examples

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

print

(

"The position of the substring is:"

,

position

)

Code analysis:

Output result:

子字符串的位置是: 7

In this example, the substring "welcome" in the string text has a starting position of index 7 in .

Document Object Reference Manual Python3 Examples