How to get the position of a character in Python?
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:
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():
To find the final act of your character, you'd want to employ str.rfind()
:
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:
For those who like to complicate easy tasks, regular expressions are your best friend:
Crystal clear visual
This string:
Find the **first 'u' seen':
Reading is like locating the right book spine:
Congratulations!
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:
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:
Extracting meaningful phrases
Use the same method to pluck out substrings from strings:
Looping like a pro
And of course, enumerate()
lets you loop through the string like a pro, no need to keep tabs on indices:
Was this article helpful?