find a substring in a string in python

In Python, you can find a substring in a string using the find() or index() method. Both methods search for the substring and return the index of the first occurrence of the substring within the string. If the substring is not found, the methods return -1.

Here's an example using the find() method:

main.py
string = "Hello, world!"
substring = "world"

index = string.find(substring)

if index != -1:
    print(f"'{substring}' found at index {index}.")
else:
    print(f"'{substring}' not found.")
191 chars
10 lines

Output:

main.py
'world' found at index 7.
26 chars
2 lines

And here's an example using the index() method:

main.py
string = "Hello, world!"
substring = "world"

try:
    index = string.index(substring)
    print(f"'{substring}' found at index {index}.")
except ValueError:
    print(f"'{substring}' not found.")
197 chars
9 lines

Output:

main.py
'world' found at index 7.
26 chars
2 lines

Note that the index() method raises a ValueError if the substring is not found, so it needs to be wrapped in a try-except block.

gistlibby LogSnag