How to find substring in a String in Python ? - Python for Data Analytics

Python Programs | Python Tricks | Solution for problems | Data Cleaning | Data Science

How to find substring in a String in Python ?

To determine the starting position of a substring in a given string str.index() function can be used where:

Syntax for using str.index() is :

str.index(substr,beg,end)

where,

str : is the main string
substr : is the substring to be searched
beg : It is an optional parameter, signifies the starting pos of search
end : It is an optional parameter, signifies the starting pos of search

Return value : index of starting position of the given substring if found else raise an error that string not found.

use of it:

str1 = "this is string example....wow!!!";
str2 = "exam";

print(str1.index(str2))

#here starting position is 10
print(str1.index(str2, 10))

#here starting position is 40
print(str1.index(str2, 40))


Screen-shot

No comments:

Post a Comment