Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Introducing .rsplit()

00:00 You are now very familiar with the .split() method, but it has a close relative called the .rsplit(). The R stands for right. It’s almost identical to the split method in most cases, but it has one key difference that it starts its work from the right end of the string.

00:16 It can be very useful in various scenarios. Let’s see some common use cases. It is very useful when you want to separate a filename from the file directory.

00:27 As I’ve mentioned before, if you’re working with file paths, it’s best to use the pathlib module. It’s cleaner, more reliable, and designed for that purpose.

00:36 If you quickly need to get a file extension or a filename, it’s perfectly fine to use the .rsplit() method, but if you’re extensively working with file parts, pathlib module is the way to go.

00:48 It is also useful in separating the major and minor version from a version number. Let’s try it on our own.

00:55 Let’s go back to our previous path example. If our path looks like this

01:05 and we want to separate the file directory from the file name, we can easily create two variables, that’s called directory and filename and use the .rsplit() method on path.

01:22 Since the filename is always the last part of the full path of a file, we’ll just set maxsplit to one. Now we have the files directory in directory variable, and we have the filename in filename variable.

01:36 Let’s print to check it out.

01:51 Now we have easily separated the filename from the file directory. By starting once from the right on the slash character, you have uniquely separated the very last component that is the filename from everything that came before it.

02:05 The real power of .rsplit() is for tasks like peeling off the last part of a string, as you saw with the file path example. Another common example would be getting the extension from a file path or extension from a name.

02:18 Always think, do I need to work from the left or with the piece I need defined by the position from the end of the string? If it’s the end, .rsplit() is the tool.

Become a Member to join the conversation.