The Wayback Machine - https://web.archive.org/web/20240926113202/https://www.geeksforgeeks.org/python-string-split/
Open In App

Python String split()

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python String split() method splits a string into a list of strings after breaking the given string by the specified separator.

Example:

Python
string = "one,two,three"
words = string.split(',')
print(words)

Output:

['one', 'two', 'three']

Python String split() Method Syntax

Syntax: str.split(separator, maxsplit)

Parameters

  • separator: This is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator.
  • maxsplit: It is a number, that tells us to split the string into a maximum of the provided number of times. If it is not provided then the default is -1 which means there is no limit.

Returns

Returns a list of strings after breaking the given string by the specified separator.

What is the list split() Method?

split() function operates on Python strings, by splitting a string into a list of strings. It is a built-in function in Python programming language.

It breaks the string by a given separator. Whitespace is the default separator if any separator is not given. 

How to use list split() method in Python?

Using the list split() method is very easy, just call the split() function with a string object and pass the separator as a parameter. Here we are using the Python String split() function to split different Strings into a list, separated by different characters in each case.

Example: In the above code, we have defined the variable ‘text’ with the string ‘geeks for geeks’ then we called the split() method for ‘text’ with no parameters which split the string with each occurrence of whitespace.

Python
text = 'geeks for geeks'

# Splits at space
print(text.split())

word = 'geeks, for, geeks'

# Splits at ','
print(word.split(','))

word = 'geeks:for:geeks'

# Splitting at ':'
print(word.split(':'))

word = 'CatBatSatFatOr'

# Splitting at t
print(word.split('t'))

Similarly, after that, we applied split() method on different strings with different delimiters as parameters based on which strings are split as seen in the output.


Output
['geeks', 'for', 'geeks']
['geeks', ' for', ' geeks']
['geeks', 'for', 'geeks']
['Ca', 'Ba', 'Sa', 'Fa', 'Or']

Time Complexity: O(n)
Auxiliary Space: O(n)

How does split() work when maxsplit is specified?

The maxsplit parameter is used to control how many splits to return after the string is parsed. Even if there are multiple splits possible, it’ll only do maximum that number of splits as defined by the maxsplit parameter.

Example: In the above code, we used the split() method with different values of maxsplit. We give maxsplit value as 0 which means no splitting will occur.

Python
word = 'geeks, for, geeks, pawan'

# maxsplit: 0
print(word.split(', ', 0))

# maxsplit: 4
print(word.split(', ', 4))

# maxsplit: 1
print(word.split(', ', 1))

The value of maxsplit 4 means the string is split at each occurrence of the delimiter, up to a maximum of 4 splits. And last maxsplit 1 means the string is split only at the first occurrence of the delimiter and the resulting lists have 1, 4, and 2 elements respectively.


Output
['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', 'pawan']
['geeks', 'for, geeks, pawan']

Time Complexity: O(n)
Auxiliary Space: O(n)

How to Parse a String in Python using the split() Method?

In Python, parsing strings is a common task when working with text data. String parsing involves splitting a string into smaller segments based on a specific delimiter or pattern. This can be easily done by using a split() method in Python.

Python
text = "Hello geek, Welcome to GeeksforGeeks."

result = text.split()
print(result)

Explanation: In the above code, we have defined a string ‘text’ that contains a sentence. By calling the split() method without providing a separator, the string is split into a list of substrings, with each word becoming an element of the list.


Output
['Hello', 'geek,', 'Welcome', 'to', 'GeeksforGeeks.']

Hope this tutorial on the string split() method helped you understand the concept of string splitting. split() method in Python has various applications like string parsing, string extraction, and many more. “How to split in Python?” is a very important question for Python job interviews and with this tutorial we have answered the question for you.

Check More: String Methods 

For more informative content related to the Python string split() method you can check the following article:

Python String split() – FAQs

What does split('\t') do in Python?

In Python, the split('\t') method splits a string into a list of substrings based on the tab (\t) delimiter. Here’s how it works:

text = "apple\tbanana\torange"
result = text.split('\t')
print(result) # Output: ['apple', 'banana', 'orange']

In this example, the split('\t') method divides the string text wherever it encounters a tab character (\t) and returns a list containing the separated substrings.

What is input().split() in Python?

input() is a built-in function in Python that reads a line from input, which is typically from the user via the console. split() is a method that splits a string into a list of substrings based on whitespace by default, or a specified delimiter. Together, input().split() allows you to read user input and split it into individual components based on whitespace.

Example:

# User input: "apple banana orange"
words = input().split()
print(words) # Output: ['apple', 'banana', 'orange']

Here, input() reads the input from the user, and split() divides the input into a list of words based on whitespace.

How to split a number in Python?

To split a number (typically an integer or float) into its individual digits, you can convert the number to a string and then split the string. Here’s an example:

number = 12345
digits = list(str(number))
print(digits) # Output: ['1', '2', '3', '4', '5']

In this example, str(number) converts the integer 12345 into a string, and list() converts the string into a list of individual characters (‘1’, ‘2’, ‘3’, ‘4’, ‘5’).

How to split a string into lines using the split() method?

To split a multi-line string into individual lines using the split() method, you can specify the newline character (\n) as the delimiter. Here’s an example:

multiline_text = "Line 1\nLine 2\nLine 3"
lines = multiline_text.split('\n')
print(lines) # Output: ['Line 1', 'Line 2', 'Line 3']

In this example, split('\n') splits the multiline_text string wherever it encounters a newline character (\n) and returns a list of lines.

How to split a string number?

If by “split a string number” you mean splitting a string representation of a number into its individual characters or parts, you can use the split() method with an empty string as the delimiter. Here’s an example:

number_str = "12345"
digits = list(number_str)
print(digits) # Output: ['1', '2', '3', '4', '5']

In this example, list(number_str) converts the string "12345" into a list of individual characters (‘1’, ‘2’, ‘3’, ‘4’, ‘5’).



Similar Reads

Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas <code
4 min read
Split a string in equal parts (grouper in Python)
Grouper recipe is an extended toolset made using an existing itertool as building blocks. It collects data into fixed-length chunks or blocks. Existing Itertools Used: izip_longest(*iterables[, fillvalue]) : Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with
2 min read
Split and Parse a string in Python
In Python, working with strings is a fundamental aspect of programming. Strings are sequences of characters and often contain structured data that needs to be processed or analyzed. The common operations performed on strings are splitting and parsing. Splitting a String in PythonIn Python, you can split a string into smaller parts using the split()
5 min read
Python | Split multiple characters from string
In Python, Strings are a basic data type that is used to store and work with textual data. Splitting a string into numerous characters is a frequent text-processing activity in Python. While coding or improvising your programming skill, you surely must have come across many scenarios where you wished to use split() in Python not to split on only on
5 min read
How to split a string in C/C++, Python and Java?
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C: // Splits str[] according to given delimiters.// and returns next token. It needs to be ca
7 min read
Split a String into columns using regex in pandas DataFrame
Given some mixed data containing multiple values as a string, let's see how can we divide the strings using regex and make multiple columns in Pandas DataFrame. Method #1: In this method we will use re.search(pattern, string, flags=0). Here pattern refers to the pattern that we want to search. It takes in a string with the following values: \w matc
3 min read
numpy string operations | split() function
numpy.core.defchararray.split(arr, sep=None, maxsplit=None) is another function for doing string operations in numpy.It returns a list of the words in the string, using sep as the delimiter string for each element in arr. Parameters: arr : array_like of str or unicode.Input array. sep : [ str or unicode, optional] specifies the separator to use whe
2 min read
Python | Pandas Reverse split strings into two List/Columns using str.rsplit()
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 provide a method to split string around a passed separator or delimiter. After that, the string can be stored as a list in a seri
3 min read
Python | Split given list and insert in excel file
Given a list containing Names and Addresses consecutively, the task is to split these two elements at a time and insert it into excel. We can use a very popular library for data analysis, Pandas. Using pandas we can easily manipulate the columns and simply insert the filtered elements into excel file using df.to_excel() function. Below is the imple
1 min read
Python PIL | Image.split() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. Image.split() method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image. Splitting an “RGB” image creates three new images each containing a copy of one of the original bands (re
1 min read
Python | Split and Pass list as separate parameter
With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let's discuss cert
4 min read
How to Split a File into a List in Python
In this article, we are going to see how to Split a File into a List in Python. When we want each line of the file to be listed at consecutive positions where each line becomes an element in the file, the splitlines() or rstrip() method is used to split a file into a list. Let's see a few examples to see how it's done. Example 1: Using the splitlin
5 min read
How to split data into training and testing in Python without sklearn
Here we will learn how to split a dataset into Train and Test sets in Python without using sklearn. The main concept that will be used here will be slicing. We can use the slicing functionalities to break the data into separate (train and test) parts. If we were to use sklearn this task is very easy but it can be a little tedious in case we are not
2 min read
Split Spark DataFrame based on condition in Python
In this article, we are going to learn how to split data frames based on conditions using Pyspark in Python. Spark data frames are a powerful tool for working with large datasets in Apache Spark. They allow to manipulate and analyze data in a structured way, using SQL-like operations. Sometimes, we may want to split a Spark DataFrame based on a spe
5 min read
Python | os.path.split() method
os.path.split() method in Python is used to Split the path name into a pair, and tail. Here, the tail is the last path name component and the head is everything leading up to that. For example, consider the following path names: path name = '/home/User/Desktop/file.txt' In the above example, the ‘file.txt’ component of the path name is tail, and ‘/
3 min read
How to split a Python list into evenly sized chunks
Iteration in Python is repeating a set of statements until a certain condition is met. This is usually done using a for loop or a while loop. There are several ways to split a Python list into evenly sized-chunks. Here are the 5 main methods: Method 1: Using a Loop with List SlicingUse for loop along with list slicing to iterate over chunks of a li
3 min read
Split a text column into two columns in Pandas DataFrame
Let's see how to split a text column into two columns in Pandas DataFrame. Method #1 : Using Series.str.split() functions. Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function. # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Name': ['J
3 min read
Split a column in Pandas dataframe and get part of it
When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement. We can use Pandas .str accessor, it does fast vectorized string operations for Series and Dataframes and returns a string object. Pandas str accessor has number of useful methods and one of them is str.spli
2 min read
Tableau - Split the text to columns
When you are working on a well defined structured data, it divides information into discrete units. For example, if you have an employee name in your data you should split it into first name, middle name and last name columns if possible. If you need to work with data that combines multiple values into a single column you can try to split the text
2 min read
Split Pandas Dataframe by column value
Sometimes in order to analyze the Dataframe more accurately, we need to split it into 2 or more parts. The Pandas provide the feature to split Dataframe according to column index, row index, and column values, etc. Let' see how to Split Pandas Dataframe by column value in Python? Now, let's create a Dataframe: villiers C/C++ Code # importing pandas
3 min read
Split Pandas Dataframe by Column Index
Pandas support two data structures for storing data the series (single column) and dataframe where values are stored in a 2D table (rows and columns). To index a dataframe using the index we need to make use of dataframe.iloc() method which takes Syntax: pandas.DataFrame.iloc[] Parameters:Index Position: Index position of rows in integer or list of
3 min read
Split large Pandas Dataframe into list of smaller Dataframes
In this article, we will learn about the splitting of large dataframe into list of smaller dataframes. This can be done mainly in two different ways : By splitting each rowUsing the concept of groupby Here we use a small dataframe to understand the concept easily and this can also be implemented in an easy way. The Dataframe consists of student id,
3 min read
How to split the element of a given NumPy array with spaces?
To split the elements of a given array with spaces we will use numpy.char.split(). It is a function for doing string operations in NumPy. It returns a list of the words in the string, using sep as the delimiter string for each element in arr. Parameters:arr : array_like of str or unicode.Input array.sep : [ str or unicode, optional] specifies the s
2 min read
Split single column into multiple columns in PySpark DataFrame
pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns. Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1) Parameters: str: str is a Column or str to split.pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression.l
4 min read
Split multiple array columns into rows in Pyspark
Suppose we have a Pyspark DataFrame that contains columns having different types of values like string, integer, etc., and sometimes the column data is in array format also. Working with the array is sometimes difficult and to remove the difficulty we wanted to split those array data into rows. Split Multiple Array Columns into Rows To split multip
5 min read
PySpark - Split dataframe into equal number of rows
When there is a huge dataset, it is better to split them into equal chunks and then process each dataframe individually. This is possible if the operation on the dataframe is independent of the rows. Each chunk or equally split dataframe then can be processed parallel making use of the resources more efficiently. In this article, we will discuss ho
3 min read
Split dataframe in Pandas based on values in multiple columns
In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame. Creating a DataFrame for demonestration C/C++ Code # importing pandas as pd import pandas a
3 min read
How to split the Dataset With scikit-learn's train_test_split() Function
In this article, we will discuss how to split a dataset using scikit-learns' train_test_split(). sklearn.model_selection.train_test_split() function: The train_test_split() method is used to split our data into train and test sets. First, we need to divide our data into features (X) and labels (y). The dataframe gets divided into X_train, X_test, y
8 min read
How can Tensorflow be used to split the flower dataset into training and validation?
The Tensorflow flower dataset is a large dataset that consists of flower images. In this article, we are going to see how we can split the flower dataset into training and validation sets. For the purposes of this article, we will use tensorflow_datasets to load the dataset. It is a library of public datasets ready to use with TensorFlow in Python.
3 min read
Split a List to Multiple Columns in Pyspark
Have you ever been stuck in a situation where you have got the data of numerous columns in one column? Got confused at that time about how to split that dataset? This can be easily achieved in Pyspark in numerous ways. In this article, we will discuss regarding same. Modules Required: Pyspark: An open source, distributed computing framework and set
5 min read
Article Tags :
Practice Tags :