Explain Codes LogoExplain Codes Logo

How to get the position of a character in Python?

python
string-methods
performance-optimization
enumerate
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
TLDR

To find out where in the string a character is hiding, utilize str.index() or str.find(). str.index() blows a ValueError if the character goes AWOL, while str.find() returns -1. Example:

phrase = "Hello, World!" loc = phrase.index('W') print(f"'W' spotted at position: {loc}") # this is not a Waldo reference

Pops out: 'W' spotted at position: 7. Remember, 0 is the hero we deserve, but not the one we acknowledge often.

When your character repeats itself

If your character has a penchant for dramatic entrances (i.e., appears multiple times), use a list comprehension with enumerate():

phrase = "Hello, World!" positions = [i for i, char in enumerate(phrase) if char == 'o'] print(f"'o' at positions: {positions}") # 'o' clearly loves making an entrance

To find the final act of your character, you'd want to employ str.rfind():

filename = 'image.png' extension_pos = filename.rfind('.') # the dot's big scene print(f"File extension begins at: {extension_pos}")

Remember you can cordone off sections of your string using start and end parameters in both find() and index() methods, should you desire to limit the search area.

Getting fancy and optimizing

If your strings are so large they have their own gravitational pull, or you’ve got efficiency on your mind, you'll want to benchmark different methods. Think of it as a performance Olympics for string methods:

import timeit print(timeit.timeit(lambda: "Hello, World!".find('W'), number = 10000)) print(timeit.timeit(lambda: "Hello, World!".index('W'), number = 10000)) # may the fastest method win!

For those who like to complicate easy tasks, regular expressions are your best friend:

import re match = re.search('n.', 'Python is fun too!') print(f"Match found at position: {match.start()}") # regex doing the heavy lifting

Crystal clear visual

This string:

"The quick brown fox jumps over the lazy dog."

Find the **first 'u' seen':

Library Shelves: | T | h | e | | q | u | i | c | k | ... | u | ... | g | . 🕵️‍♂️ 🏆

Reading is like locating the right book spine:

position = "The quick brown fox jumps over the lazy dog.".find('u')

Congratulations!

Located the 'u' at: 🏆 **5** # Remember, Python starts counting at 0!

Anticipating curveballs

Life's easy when everything goes as per the plan, but here in programming land, we love a good dose of chaos. So remember to handle exceptions, like missing or repeated characters:

try: loc = my_string.index('x') except ValueError: loc = "Character entered witness protection." # exceptions are like # annoying siblings. Handle them.

Massaging filenames and paths

String methods can also help you with filenames and file paths. To get a filename without its extension, use some rfind() and string slicing wizardry:

filename = "photo.jpg" basename = filename[:filename.rfind('.')] print(f"Basename: {basename}") # separator anxiety

Extracting meaningful phrases

Use the same method to pluck out substrings from strings:

quote = "Stay hungry, stay foolish" key_motif = quote[quote.find('hungry') : quote.find('hungry') + len('hungry')] print(f"Key motif: {key_motif}") # feeling hungry yet?

Looping like a pro

And of course, enumerate() lets you loop through the string like a pro, no need to keep tabs on indices:

for spot, letter in enumerate("Hello, World!"): if letter == 'o': print(f"'o' spotted at position: {spot}") # 'o' can't hide for long