1foo = "abcdefc"
2
3# Using find()
4foo.find('c')
5# Output: 2
6foo.find('g')
7# Output: -1
8
9# Using index()
10# foo.index() is like foo.find(),
11# But when the substring is not found, it raises an exception.
12foo.index('h')
13# ValueError: substring not found
1word = 'Hello'
2to_find = 'l'
3
4# in one line
5print([i for i, x in enumerate(word) if x == to_find])
1string = "Hello World"
2string_slice = string[1:10] # "ello Worl" (index 1 up to 10)
3string_last_chars = string[-5:] # "World" (5th index from last to the end)
4H = string[0] # "H"
1my_var = 'mummy'. #Find the position of 'm'
2
3#Using find - find returns the index for the first instance from the left.
4my_var.find('m')
5# Output: 0
6
7#Using rfind - rfind returns the index for the first instance from the right.
8my_var.rfind('m')
9# Output: 3
10# With find() and rfind(), when substring is not found, it returns -1.
11
12#NB: You can use index() and rindex(). In this case, when the substring is not
13# found, it raises an exception.
1import re
2# matches_position_start will be a list of starting index positions
3matches_start = re.finditer(word.lower(), string.lower())
4matches_position_start = [match.start() for match in matches_start]
5
6# matches_position_end will be a list of ending index positions
7matches_end = re.finditer(word.lower(), string.lower())
8matches_position_end = [match.end() for match in matches_end]