The Wayback Machine - https://web.archive.org/web/20240930220454/https://www.geeksforgeeks.org/python-string-partition-method/
Open In App

Python String partition() Method

Last Updated : 22 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python String partition() method splits the string at the first occurrence of the separator and returns a tuple containing the part before the separator, the separator, and the part after the separator. Here, the separator is a string that is given as the argument.

Example: 

Python3




str = "I love Geeks for geeks"
print(str.partition("for"))


Output: 

('I love Geeks ', 'for', ' geeks')

Python String partition() Method Syntax

Syntax: string.partition(separator)

Parameters: 

  • separator: a substring that separates the string

Return: Returns a tuple of 3 elements. The substring before the separator, the separator, the part after the separator.

String partition() in Python Examples

Working of Python String partition() Method

In this example, we are demonstrating the use of the partition() method in Python with two separators attracts and is.

Python3




string = "light attracts bug"
# 'attracts' separator is found
print(string.partition('attracts'))
 
string = "gold is heavy"
# 'is' as partition
print(string.partition('is'))


Output: 

('light ', 'attracts', ' bug')
('gold ', 'is', ' heavy')

The partition() Method only partitions on the first occurrence of the separator

In this example, we are showing that the Python String partition() Method only considers the first occurrence of the separator in the string. When the first occurrence of the separator will occur the string will be separated.

Python3




string = "b follows a, c follows b"
print(string.partition('follows'))
 
string = "I am happy, I am proud"
print(string.partition('am'))


Output: 

('b ', 'follows', ' a, c follows b')
('I ', 'am', ' happy, I am proud')

Result of partition() Method when the separator is missing from the String

In this example, We are showing that the Python String partition() Method returns the original string as the first element of the tuple, and the remaining two elements are empty. As you can see ‘are’ is missing from the string ‘geeks for geeks’.

Python3




string = "geeks for geeks"
print(string.partition('are'))


Output:

('geeks for geeks', '', '')

Used Partition() Method to get a domain name from the String

In this example, We are using the partition() to get the domain name of the URL String. 

Python3




result = url.partition("//")
result = result[2].partition("/")
print(result[0])


Output:

www.example.com

Case sensitive Python

In this example, we are using two different case-sensitive separators fox and Fox, which return different tuples.

Python3




sentence = "The quick Brown fox jumps over the lazy Fox."
result = sentence.partition("fox")
print(result)
result = sentence.partition("Fox")
print(result)


Output:

('The quick Brown ', 'fox', ' jumps over the lazy Fox.')
('The quick Brown fox jumps over the lazy ', 'Fox', '.')


Previous Article
Next Article

Similar Reads

Python | sympy.partition() method
With the help of sympy.partition() method, we can find Partition number in SymPy. partition(n) - The Partition numbers are a sequence of integers pn that represent the number of distinct ways of representing n as a sum of natural numbers (with order irrelevant). The generating function for pn is given by - [Tex]\sum_{n=0}^\infty p_n x^n = \prod_{k=
1 min read
Python | sympy Partition() method
With the help of sympy.combinatorics.partitions.Partition() method, we are going to separate the members of arrays into one tuple by using sympy.combinatorics.partitions.Partition() method. Syntax : sympy.combinatorics.partitions.Partition(array) Return : Return a members of arrays into one tuple. Example #1 : In this example we can see that by usi
1 min read
Python | SymPy Partition.sort_key() method
Partition.sort_key() : sort_key() is a sympy Python library function that returns canonical key which can be used for string. This ordering of canonical key is based on the size and the elements of the partition whose ties are broken with the rank. Syntax : sympy.combinatorics.partitions.Partition.sort_key() Return : Canonical key which can be used
1 min read
Numpy string operations | partition() function
In the numpy.core.defchararray.partition() function, each element in arr, split the element as the first occurrence of sep, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings
1 min read
Python | Pandas Series.str.partition()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.partition() works in a similar way like str.split(). Instead of splitting the string at every occurrence of separator/delimit
3 min read
numpy.partition() in Python
numpy.partition() function is used to create a partitioned copy of input array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering
2 min read
Python | Numpy matrix.partition()
With the help of Numpy matrix.partition() method, we are able to partition the matrix in such a way that index value that we pass sort the matrix like all the values smaller than that value is move left to it and others are right with the help of matrix.partition() method. Syntax : matrix.partition(index) Return : Return partitioned matrix Example
1 min read
SymPy | Partition.RGS_generalized() in Python
Partition.RGS_generalized() : RGS_generalized() is a sympy Python library function that calculates the m + 1 generalized unrestricted growth strings (string where a[i] is the block in which element i occurs) and then return it as rows in matrix. Restricted growth strings - string in which each character, ai results in the Block (Bi) in which the co
1 min read
SymPy | Partition.RGS_enum() in Python
Partition.RGS_enum() : RGS_enum() is a sympy Python library function that calculates the total number of restricted growth strings (string where a[i] is the block in which element i occurs) which is possible for a superset of size n. Restricted growth strings - string in which each character, ai results in the Block (Bi) in which the corresponding
2 min read
SymPy | Partition.RGS_rank() in Python
Partition.RGS_rank(rank, n) : RGS_rank() is a sympy Python library function that gives the rank for a restricted growth strings (string where a[i] is the block in which element i occurs) . Restricted growth strings - string in which each character, ai results in the Block (Bi) in which the corresponding element belongs. Syntax : sympy.combinatorics
1 min read
SymPy | Partition.RGS_unrank() in Python
Partition.RGS_unrank(rank, n) : RGS_unrank() is a sympy Python library function that gives the unranked restricted growth strings (string where a[i] is the block in which element i occurs) for a superset of size n. Restricted growth strings - string in which each character, ai results in the Block (Bi) in which the corresponding element belongs. Sy
1 min read
SymPy | Partition.as_ferrers() in Python
Partition.as_ferrers() : as_ferrers() is a sympy Python library function that returns the ferrer diagram of a partition as per the character mentioned. Syntax : sympy.combinatorics.partitions.Partition.as_ferrers(char) Return : ferrer diagram of a partition Code #1 : as_ferrers() Example # Python code explaining # SymPy.as_ferrers() # importing Sym
1 min read
SymPy | Partition.as_dict() in Python
Partition.as_dict() : as_dict() is a sympy Python library function that returns the partition as a dictionary. In this dictionary, the keys are the partition integers. The values are the multiplicity of that integer. Syntax : sympy.combinatorics.partitions.Partition.as_dict() Return : Partition as a dictionary Code #1 : as_dict() Example # Python c
1 min read
Numpy recarray.partition() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record arrays allow the fields to be accessed as members of th
3 min read
How to re-partition pyspark dataframe in Python
Are you a data science or machine learning enthusiast who likes to play with data? Have you ever got the need to repartition the Pyspark dataset you got? Got confused, about how to fulfill the demand? Don't worry! In this article, we will discuss the re-partitioning of the Pyspark data frame in Python. Modules Required:Pyspark: spark library which
3 min read
SymPy | Partition.prev_lex() in Python
Partition.prev_lex() : prev_lex() is a sympy Python library function that returns the previous integer partition, n in lexicographical order. This ordering wraps around [n] if the partition is [1, …, 1]. Syntax : sympy.combinatorics.partitions.Partition.prev_lex()Return : previous integer partition, n in lexicographical order Code #1 : prev_lex() E
1 min read
SymPy | Partition.next_lex() in Python
Partition.next_lex() : next_lex() is a sympy Python library function that returns the next integer partition, n in lexicographical order. This ordering wraps around [n] if the partition is [1, …, 1]. Syntax : sympy.combinatorics.partitions.Partition.next_lex() Return : next integer partition, n in lexicographical order Code #1 : next_lex() Example
1 min read
SymPy | Partition.conjugate() in Python
Partition.conjugate() : conjugate() is a sympy Python library function that returns the conjugate partition of the argumented partition. Syntax : sympy.combinatorics.partitions.Partition.conjugate() Return : conjugate partition Code #1 : conjugate() Example [GFGTABS] Python3 1=1 # Python code explaining # SymPy.conjugate() # importing SymPy librari
3 min read
How to See Record Count Per Partition in a pySpark DataFrame
The API which was introduced to support Spark and Python language and has features of Scikit-learn and Pandas libraries of Python is known as Pyspark. Whenever we upload any file in the Pyspark, it creates a partition of that data equal to the number of cores. The user can repartition that data and divide it into as many partitions as he wants. Thu
4 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: [GFGTABS] Python string = "Geeksforgeeks" print(len(string)) [/GFGTABS]Output13String len() Syntaxlen(string) ParameterString: string of which you want to find the length. Retu
5 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Article Tags :
Practice Tags :