How to Find a Substring in a String with Python


In this example, we will learn how to find a substring in a string with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

str1 = input("Please input a string: ")
str2 = input("Please input another string: ")
index = str1.find(str2)
print('\nIndex of the second string: %s'%index)

Output:

Please input a string: dhfhagad
Please input another string: ga
Index of the second string: 5

Please input a string: dhfhagad
Please input another string: gah
Index of the second string: -1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement