search for a character in a string in python
Code snippet on how to search for a character in a string in python
word = 'programming'
# to find the character 'r'
index = 0
for char in word:
if char == 'r':
break
index += 1
print("Index of character 'r' is:", index)
This code searches for the character ‘r’ inside the string ‘programming’. First, it sets the index to 0. Next, it loops through each character of the string (in this case ‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘m’, ‘i’, ‘n’, ‘g’). For every loop, it checks to see if the character is equal to ‘r’, and if it is, it breaks out of the loop. If it isn’t, it adds one to the index. Once the loop is finished, it prints the index of the character ‘r’. In this case, it would be 1.