Python sub-strings

The find(), rfind(), index() and rindex() methods are useful to locate sub strings in a string. These methods return the location of the first occurrence of the sub string in the main string. The find() and index() methods search for the sub string from the beginning of the main string.

sub-string examples

The rindex() and rfind() methods return the highest index of the substring inside the string (if found). If the substring is not found, it raises an exception.

The find() method returns -1 if the sub string is not found in the main string.

The index() method returns 'ValueError' exception if the sub string is not found. The format of find() method is: mainstring.find(substring, beginning, ending) The same format is used for other methods also.

A Python program to find the first occurrence of sub string in a given main string.

CopiedCopy Code

str = input('Enter main string:') 
sub = input('Enter sub string:') 
n = str.find(sub, 0, len(str)) 
if n == -1: 
print('Sub string not found') 
else: 
print('Sub string found at position:', n+1)

A Python program to find the first occurrence of sub string in a given string using index() method.

CopiedCopy Code

str = input('Enter main string:') 
sub = input('Enter sub string:') 
try: 
  n = str.index(sub, 0, len(str)) 
except ValueError: 
print('Sub string not found') 
else: 
print('Sub string found at position:', n+1)