Python .partition()

Anonymous contributor's avatar
Anonymous contributor
Published Jun 9, 2021Updated Oct 13, 2023
Contribute to Docs

Searches a string for a given keyword and splits that string into a three part tuple.

  • Learn to analyze and visualize data using Python and statistics.
    • Includes 8 Courses
    • With Certificate
    • Intermediate.
      13 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

string.partition("keyword")

Example

The .partition() method searches for an exact match of the given keyword:

my_string = "Do not go gentle into that good night"
my_tuple = my_string.partition("gentle")
print(my_tuple)
# Output: ('Do not go ', 'gentle', ' into that good night')

No Match Found

If no match is found, .partition() will return a tuple with the full string, followed by two empty strings

Code
Output

Multiple Matches

If there are multiple matches, the first one will be used:

Code
Output

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Learn to analyze and visualize data using Python and statistics.
    • Includes 8 Courses
    • With Certificate
    • Intermediate.
      13 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours