Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python String rpartition() Method
Next article icon

Python String rpartition() Method

Last Updated : 05 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

String rpartition() method in Python is a powerful tool for splitting a string into three parts, based on the last occurrence of a specified separator. It provides an efficient way to handle text parsing when we want to divide strings from the rightmost delimiter.

Let us start with a simple example:

Python
s = "welcome to Python programming"  # Using rpartition to split from the last occurrence of the space character res = s.rpartition(" ") print(res)  

Output
('welcome to Python', ' ', 'programming') 

Explanation

  • The string 's' is split into three parts: the part before the last space, the space itself, and the part after the space.
  • The method ensures that the splitting happens only at the last occurrence of the specified separator. This is particularly useful when we want to isolate specific segments from the end of the string.

Table of Content

  • Syntax of rpartition() method
  • Examples of rpartition() method

Syntax of rpartition() method

string.rpartition(separator)

Parameters

  • separator (required): The string based on which the split occurs. It can be any character or substring.

Return Type

  • Returns a tuple of three elements: (part_before, separator, part_after).
  • If the separator is not found, it returns (' ', ' ', original_string).

Examples of rpartition() method

1. Splitting using a space separator

The rpartition() method can be handy when we want to isolate the last segment of a sentence. For instance, separating the last word of a sentence for further processing

Python
s = "Data Science and Machine Learning"  # Splitting from the last occurrence of space res = s.rpartition(" ")  print(res)  

Output
('Data Science and Machine', ' ', 'Learning') 

Explanation

  • The method searches for the last occurrence of the space character.
  • The string is divided into three parts: the text before the space, the space itself, and the text after the space.

2. When the separator is not found

Sometimes, the separator we specify may not exist in the string. In such cases, the method returns the entire string as the last element in the tuple.

Python
s = "NoSeparatorHere" # Attempting to split with a separator not present in the string res = s.rpartition("-") print(res)   

Output
('', '', 'NoSeparatorHere') 

Explanation

  • This method ensures that the output format of the method is consistent, making it predictable in situations where the separator may or may not exist.

3. Using a specific character as the separator

The rpartition() method is particularly useful for splitting structured data like dates or timestamps. For instance, it can help isolate the day from a date string.

Python
s = "2024-12-27"  # Splitting the date string from the last occurrence of '-' res = s.rpartition("-") print(res)   

Output
('2024-12', '-', '27') 

Explanation

  • The method identifies the last occurrence of the '-' character.
  • The string is split into the year and month part, the separator, and the day part.

4. Combining rpartition() with other methods

The rpartition() method is often combined with other operations.

Python
s = "path/to/the/file.txt"  # Extracting the directory and filename directory, separator, filename = s.rpartition("/") print("Directory:", directory)  print("Filename:", filename)     

Output
Directory: path/to/the Filename: file.txt 

Explanation

  • The method is used to split a file path into the directory and the filename.
  • This demonstrates how we can use the rpartition() method in real-world scenarios like file manipulation or directory navigation.
  • It is particularly helpful for systems or tools that need to separate file paths into meaningful components.

Next Article
Python String rpartition() Method

K

Kanchan_Ray
Improve
Article Tags :
  • Python
  • Python-Built-in-functions
  • python-string
Practice Tags :
  • python

Similar Reads

    Python String islower() Method
    The islower() method in Python checks if all characters in a string are lowercase. It returns True if all alphabetic characters are lowercase, otherwise, it returns False, if there is at least one uppercase letter.Let's look at a quick example of using the islower() method.Pythons = "hello" res = s.
    2 min read
    Python String isnumeric() Method
    The isnumeric() method is a built-in method in Python that belongs to the string class. It is used to determine whether the string consists of numeric characters or not. It returns a Boolean value. If all characters in the string are numeric and it is not empty, it returns “True” If all characters i
    3 min read
    Python String isprintable() Method
    Python String isprintable() is a built-in method used for string handling. The isprintable() method returns "True" if all characters in the string are printable or the string is empty, Otherwise, It returns "False". This function is used to check if the argument contains any printable characters suc
    3 min read
    Python String isspace() Method
    isspace() method in Python is used to check if all characters in a string are whitespace characters. This includes spaces (' '), tabs (\t), newlines (\n), and other Unicode-defined whitespace characters. This method is particularly helpful when validating input or processing text to ensure that it c
    2 min read
    Python String istitle() Method
    The istitle() method in Python is used to check whether a string follows the title case formatting. In a title-cased string, the first letter of each word is capitalized, and all other letters in the word are in lowercase. This method is especially useful when working with formatted text such as tit
    3 min read
    Python String isupper() method
    isupper() method in Python checks if all the alphabetic characters in a string are uppercase. If the string contains at least one alphabetic character and all of them are uppercase, the method returns True. Otherwise, it returns False. Let's understand this with the help of an example:Pythons = "GEE
    3 min read
    Python String join() Method
    The join() method in Python is used to concatenate the elements of an iterable (such as a list, tuple, or set) into a single string with a specified delimiter placed between each element.Lets take a simple example to join list of string using join() method.Joining a List of StringsIn below example,
    3 min read
    String lower() Method in Python
    lower() method in Python converts all uppercase letters in a string to their lowercase. This method does not alter non-letter characters (e.g., numbers, punctuation). Let's look at an example of lower() method:Pythons = "HELLO, WORLD!" # Change all uppercase letters to lowercase res = s.lower() prin
    3 min read
    Python String lstrip() Method
    The lstrip() method removes leading whitespace characters from a string. We can also specify custom characters to remove from the beginning/starting of the string.Let's take an example to remove whitespace from the starting of a string.Pythons = " Hello Python!" res = s.lstrip() print(res)OutputHell
    2 min read
    Python String partition() Method
    In Python, the String partition() method splits the string into three parts at the first occurrence of the separator and returns a tuple containing the part before the separator, the separator itself, and the part after the separator. Let's understand with the help of an example:Pythons = "Geeks gee
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences