Python: Position of next occurrence of a sub-string

Python code to get the position of next or second occurrence of a sub-string within a string.

# Below code finds the position of second occurrence of "xyz"
string = "xyz is equal to xyz"
firstSubPos=string.find("xyz") # get the position of first substring "xyz"
secondSubPos=string.find("xyz", firstSubPos+1) # get the position of second occurence of substring "xyz"
print "position of second occurence of substring \"xyz\" is " + str(secondSubPos) # print the position

Note: Above code works in both Python 2 and Python 3

Output:
position-of-second-occurence-python

Read -> Strip trailing whitespaces from string [Python]

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published. Required fields are marked *