
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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')