Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

partition
string
python
communitycreator

What is the string.partition() method in python?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The partition method will split the first occurrence of string_B in string_A and returns a tuple with three items.

  • The first item contains the part of a string the before string_B.

  • The second item contains the string_B itself.

  • The third item contains the part of the string after the string_B.

If the string_B is not present in a string, then a tuple with the string_A and two empty strings is returned. That is, (string_A, '', '') is returned.

Syntax


string_A.partition(string_B)

Code

Example 1

string = "this test is a test"
tup = string.partition('test')
print(tup)

Explanation 1

In the cobe above, we created a string this test is a test and called partition('test'). This will split the string at the first occurrence of the substring test and return a tuple containing three items.

  • First item: Part of the string before the first occurrence of test substring. In our case, it is this.

  • Second item: Separator string itself. In our case, it is a test.

  • Third item: Part of the string after the first occurrence of test substring. In our case, it is " is a test".

Example 2

string = "this test is a test"
tup = string.partition('best')
print(tup)

Explanation 2

In the example above, we created a string this test is a test and called partition('best'), but the string has no substring best, so the partition method will return a tuple containing three items.

  • First item: Source string. In our case, this test is a test.

  • Second and third items: Empty string.

RELATED TAGS

partition
string
python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring