Find All Character Positions in a String with Python
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This Python code demonstrates how to find all positions of a specific character within a string. It uses the find() method inside a while loop.
- The string
fruits = 'apple and banana'is defined, and the target character is'a'. - The variable
indexacts as the starting point for the search and is initially set to0. - In each iteration,
find()returns the first index of the character from the current index. - If
find()returns-1, the character is not found, and the loop breaks. - Otherwise, the found index is added to the
positionslist, and the index is incremented by1to continue the search after that position.
Finally, the list of positions is printed. This approach is useful for finding all occurrences of a pattern in a string efficiently.