OneBite.Dev - Coding blog in a bite size

find the index of a substring within a string in python

Code snippet on how to find the index of a substring within a string in python

string = 'Hello world!'

substring = 'world'

index = string.find(substring)

This code will find the index of a substring within a string in Python. First, two strings are created. The first string is called “string” and it holds the value ‘Hello world!‘. The second string is called “substring” and it holds the value ‘world’. Then an index is created and the value is assigned by using the .find() method on the “string” and passing in the “substring” as an argument. This method looks for the substring within the string and returns the index at which it is found. If the substring is not found, then the .find() method returns -1.

python