Split String by Delimiter in Python



While working with the strings in python, we will find the situations to break the string into parts. This is called splitting a string and is usually done based on a delimiter, this is nothing but a character or sequence of characters that separate the parts of the string.

Python provides the several ways for achieving this, depending on whether the delimiter is simple string or a pattern. Let's dive into the article to learn more about splitting string by delimiter.

Using python split() Method

The python split() method is used to split the words in a string separated by a specified separator. This separator is a delimiter string, and can be a comma, full-stop, space character or any other character used to separate strings.

Syntax

Following is the syntax of python split() method ?

str.split(separator, maxsplit)

Example 1

Let's look at the following example, where we are going to consider the basic usage of the split() method.

str1 = "Welcome to Tutorialspoint"
print(str1.split())

Output

Output of the above program is as follows ?

['Welcome', 'to', 'Tutorialspoint']

Example 2

Consider the another scenario, where we are going to use the maxsplit to limit the splits.

str1 = "Ciaz, Audi, BMW"
print(str1.split(',',1))

Output

Output of the above program is as follows ?

['Ciaz', ' Audi, BMW']

Using python re.split() Method

The python re.split() method is used to split the string by the occurrences of a specified regular expression pattern.

Syntax

Following is the syntax for python re.split() method ?

re.split(<pattern>, string, <maxsplit>)

Example

Consider the following example, where we are going to use the format() method to align the text to right.

import re
str1 = "Welcome to Tutorialspoint"
print(re.split(' ',str1))

Output

Following is the output of the above program ?

['Welcome', 'to', 'Tutorialspoint']

Using Python partition() Method

The python partition() method is used to split a string into three parts based on the first occurrence of a specified separator. It returns a tuple containing three elements.

If the separator is not found in the string, the entire string is returned as the first element of the tuple, followed by two empty strings.

Syntax

Following is the syntax of Python partition() method ?

str.partition(value)

Example

In the following example, we are splitting the string "text" at the first occurrence of the space " " character using the partition() method.

text = "TP TutorialsPoint"
result = text.partition(' ')
print(result)

Output

If we run the above program, it will generate the following output ?

('TP', ' ', 'TutorialsPoint')
Updated on: 2025-04-11T12:03:31+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements