find string index in python code example

Example 1: python string indexing

str = 'codegrepper'
# str[start:end:step]
#by default: start = 0, end = len(str), step = 1
print(str[:]) 		#codegrepper
print(str[::]) 		#codegrepper
print(str[5:]) 		#repper
print(str[:8]) 		#codegrep
print(str[::2]) 	#cdgepr
print(str[2:8]) 	#degrep
print(str[2:8:2]) 	#dge
#step < 0 : reverse
print(str[::-1]) 	#reppergedoc
print(str[::-3]) 	#rpgo
# str[start:end:-1]	means start from the end, go backward and stop at start
print(str[8:3:-1]) 	#pperg

Example 2: python string index of

sentence = 'Python programming is fun.'

result = sentence.index('is fun')
print("Substring 'is fun':", result)

result = sentence.index('Java')
print("Substring 'Java':", result)

Example 3: how to find the indexes of a substring in a string in python

import re
# matches_position_start will be a list of starting index positions
matches_start = re.finditer(word.lower(), string.lower())
matches_position_start = [match.start() for match in matches_start]

# matches_position_end will be a list of ending index positions
matches_end = re.finditer(word.lower(), string.lower())
matches_position_end = [match.end() for match in matches_end]