Removing Prefixes and Suffixes
00:00 The strip methods you’ve seen so far are great for removing specific characters found on the ends of strings, in any order. But when you want to remove an entire sequence of characters and only that sequence from either end of a string, you’ll need a different tool.
00:14
The .removeprefix()
method removes a prefix, a sequence of characters from the start of an existing string, while the .removesuffix()
method removes a suffix, a sequence of characters at the end of a string.
00:25 Both methods take a string argument, the suffix or prefix you want removed. As per usual, you’ll explore examples in the REPL.
00:34
Start by creating a new string called filename
with the contents txt_transcript.txt
.
00:43
And say you want to remove the leading txt_
from this file using the .strip()
method. Try filename.strip("txt_")
,
00:53
and the result is ranscrip.
. Nope, that’s not it. Remember, .strip()
removes all matching characters from both ends of a string.
01:04
Instead, try filename.removeprefix(
"txt_")
. transcript.txt
, perfect. But remember, this method is meant to remove an exact sequence.
01:17
So if you alter it slightly like this: filename.
removeprefix("_txt")
, you end up with the same txt_transcript.txt
string that you started with.
01:31
Because filename
doesn’t start with "txt"
, nothing happens.
01:37
Removing suffixes can be done much the same. For example, if you want to remove the file extension, call filename.removesuffix(".txt")
, leaving you with simply txt_transcript
.
01:52
Again, if the suffix isn’t found, nothing will happen. If you call filename.removesuffix("mp3")
,
02:00
the result is still txt_transcript.txt
. These methods are especially useful when you’re dealing with fairly consistent strings that have prefixes or suffixes that you want to remove.
02:12
But if you’re working with filenames specifically, you’ll probably want to reach for the built-in pathlib
module instead. With it, you can convert the string filename
into a Path
object, which has methods and attributes designed to make file handling easier, especially for code that might run on different operating systems. From pathlib
import Path
and create a Path
object called file
.
02:35
file =
the result of passing filename
into the Path
constructor.
02:40
And now if you want the filename without the extension, you can grab it from the .stem
attribute. file.stem
returns txt_transcript
.
02:49 Great. Next up, you’ll take a look at the most common mistakes people make when stripping characters from strings and how to avoid them.
Become a Member to join the conversation.