Python .split() – Splitting a String in Python

Dionysia Lemonaki

In this article, you will learn how to split a string in Python.
Firstly, I’ll introduce you to the syntax of the .split() method. After that, you will see how to use the .split() method with and without arguments, using code examples along the way.
Here is what we will cover:
What Is The .split() Method in Python? .split() Method Syntax Breakdown
You use the .split() method for splitting a string into a list.
The general syntax for the .split() method looks something like the following:
Let’s break it down:
- string is the string you want to split. This is the string on which you call the .split() method.
- The .split() method accepts two arguments.
- The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .split() encounters any whitespace.
- The second optional argument is maxsplit , which specifies the maximum number of splits the .split() method should perform. If this argument is not provided, the default value is -1 , meaning there is no limit on the number of splits, and .split() should split the string on all the occurrences it encounters separator .
The .split() method returns a new list of substrings, and the original string is not modified in any way.
How Does The .split() Method Work Without Any Arguments?
Here is how you would split a string into a list using the .split() method without any arguments:
The output shows that each word that makes up the string is now a list item, and the original string is preserved.
When you don’t pass either of the two arguments that the .split() method accepts, then by default, it will split the string every time it encounters whitespace until the string comes to an end.
What happens when you don’t pass any arguments to the .split() method, and it encounters consecutive whitespaces instead of just one?
In the example above, I added consecutive whitespaces between the word love and the word coding . When this is the case, the .split() method treats any consecutive spaces as if they are one single whitespace.
How Does The .split() Method Work With The separator Argument?
As you saw earlier, when there is no separator argument, the default value for it is whitespace. That said, you can set a different separator .
The separator will break and divide the string whenever it encounters the character you specify and will return a list of substrings.
For example, you could make it so that a string splits whenever the .split() method encounters a dot, . :
In the example above, the string splits whenever .split() encounters a .
Keep in mind that I didn’t specify a dot followed by a space. That wouldn’t work since the string doesn’t contain a dot followed by a space:
Now, let’s revisit the last example from the previous section.
When there was no separator argument, consecutive whitespaces were treated as if they were single whitespace.
However, when you specify a single space as the separator , then the string splits every time it encounters a single space character:
In the example above, each time .split() encountered a space character, it split the word and added the empty space as a list item.
How Does The .split() Method Work With The maxsplit Argument?
When there is no maxsplit argument, there is no specified limit for when the splitting should stop.
In the first example of the previous section, .split() split the string each and every time it encountered the separator until it reached the end of the string.
However, you can specify when you want the split to end.
For example, you could specify that the split ends after it encounters one dot:
In the example above, I set the maxsplit to 1 , and a list was created with two list items.
I specified that the list should split when it encounters one dot. Once it encountered one dot, the operation would end, and the rest of the string would be a list item on its own.
Conclusion
And there you have it! You now know how to split a string in Python using the .split() method.
I hope you found this tutorial helpful.
To learn more about the Python programming language, check out freeCodeCamp’s Python certification.
You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
split¶
Returns a list of the words in the string, separated by the delimiter string.
Syntax¶
str. split([sep[, maxsplit]])
sep Optional. Character dividing the string into split groups; default is space. maxsplit Optional. Number of splits to do; default is -1 which splits all the items.
Return Value¶
list
Time Complexity¶
Remarks¶
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,
returns [‘1’, ‘’, ‘2’]). The sep argument may consist of multiple characters (for example,
returns [‘1’, ‘2’, ‘3’]). Splitting an empty string with a specified separator returns [‘’].
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
Python String split()
The split() function in Python is used to split a given string into a list of small substrings according to a separator and finally it returns that list where elements are nothing but the split parts of the string.
Syntax of Split () Function in Python
The syntax of split() is as follows:
The myString is the string on which the split function called.
Parameters of Split () Function in Python
split() function in Python takes two parameters:
- separator : The separator is the character by which the main string is to be split into smaller substrings. If it is not provided the whitespace is considered as separator by default.
- maxCount : It tells the number of times the string should be split, It is a number value and if not provided, by default it is -1 that means there is no limit.
Return Value of Split () Function in Python
Return Type: list
This Function returns a python list containing the split strings.
Example of split() in Python
Here we are going to discuss a simple example based on the split function.
Code:
Output:
Explanation:
The string S1 is split by whitespaces as we have not provided any separator, The string S2 is split by commas. Subsequently list for both is being returned.
What is split() function in Python?
Take a case where you have given a list of names separated by commas and you have to separate all of them and display them,
In that case, you can use the split() function that will easily separate all the names by commas, and then you can easily display them.
As the name suggests, the split() function in python is used to split a particular string into smaller strings by breaking the main string using the given specifier. The specifier is the character separator to use while splitting the string, for example — "@", " ", '$' , etc.
Why use split() function in Python?
Suppose there is a condition where you have given a string "This@is@scaler" and you have to get all the words of this string in a list. So, in that case we have to split the whole string by "@" character and that’s where the split() function comes in handy. So, the function will create a list ['This', 'is', 'scaler'] .
It easily splits the above string by "@" and gives the list containing all the smaller strings.
Similarly it easily splits the above string by whitespaces and gives the list containing all the smaller strings, so the list will be ['Hello', 'World'] .
More Examples of Split () Function in Python
Example 1: Using maxCount Parameter
We can set the Maximum Number of parts in which string should be split.
Code:
Output:
Explanation:
The string S1 will be split at whitespaces three times as we have provided max parameter as 3 . The string S2 will be split at '@' two times as we have provided max parameter as 2
Example 2: Combining the Returned Array.
We can also do other useful operations on returned list i.e. combining it into a single string.
Code:
Output:
Explanation:
String S1 is split by '#' and then is stored in a list and further join operations is performed on that list subsequently the list combines to the new string.
Что делает функция split в Python?

Получается split(), превращает в список любое предложение, если поставить ",", то-есть split(" , ") то мы игнорируем , и просто все слова пишем как в списке, в кавычках и через запятую. Если не понятно то когда мы вставляем запятую, получается пайтон думает так: словом будет то где заканчивается запятая тоесть 1 3, 45 , 45,; пайтон выыедет ["1 3", "45 ", " 45"].

Всем всем всем 🙂 По умолчанию любой пробел является разделителем. Под любым пробелом, в том числе подразумеваются: управляющие комбинации разделителей типа "\t" или "\n". Эта новость сэкономит Вам пару -тройку строк и нервных клеток, если требуется разделить на элементы строку по пробелам, табуляции и переносу.

Получается split(), превращает в список любое предложение, если поставить ",", то-есть split(" , ") то мы игнорируем , и просто все слова пишем как в списке, в кавычках и через запятую.

Метод split() в Python разделяет строку на список подстрок по разделителю.