8.3 Searching/testing strings
Learning objectives
By the end of this section you should be able to
- Use the
inoperator to identify whether a given string contains a substring. - Call the
countmethod to count the number of substrings in a given string. - Search a string to find a substring using the
findmethod. - Use the
indexmethod to find the index of the first occurrence of a substring in a given string. - Write a for loop on strings using in operator.
in operator
The in Boolean operator can be used to check if a string contains another string. in returns True if the first string exists in the second string, False otherwise.
For loop using in operator
The in operator can be used to iterate over characters in a string using a for loop. In each for loop iteration, one character is read and will be the loop variable for that iteration.
count
The count method counts the number of occurrences of a substring in a given string. If the given substring does not exist in the given string, the value 0 is returned.
find
The find method returns the index of the first occurrence of a substring in a given string. If the substring does not exist in the given string, the value of -1 is returned.
index
The index method performs similarly to the find method in which the method returns the index of the first occurrence of a substring in a given string. The index method assumes that the substring exists in the given string; otherwise, throws a ValueError.