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.py191 chars10 lines
Output:
main.py26 chars2 lines
And here's an example using the index()
method:
main.py197 chars9 lines
Output:
main.py26 chars2 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