- split¶
- Syntax¶
- Return Value¶
- Time Complexity¶
- Remarks¶
- Example 1¶
- Example 2¶
- Example 3¶
- See Also¶
- Python String split() Method
- Definition and Usage
- Syntax
- Parameter Values
- More Examples
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Изучаем метод split Python 3
- Метод split в питоне — синтаксис
- Функция split Python — параметры
- Возвращаемое значение в split()
- Как работает метод split Python 3 — пример
- Выполнение split() при заданном maxsplit — пример
- Python String split()
- Syntax of Split () Function in Python
- Parameters of Split () Function in Python
- Return Value of Split () Function in Python
- Example of split() in Python
- What is split() function in Python?
- Why use split() function in Python?
- More Examples of Split () Function in Python
- Example 1: Using maxCount Parameter
- Example 2: Combining the Returned Array.
- Conclusion
- See Also:
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¶
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 [].
Example 1¶
>>> ' a b c '.split() ['a', 'b', 'c'] >>> ' a b c '.split(None) ['a', 'b', 'c'] >>> ' a b c '.split(' ', 1) ['', 'a b c '] >>> ' a b c '.split(' ', 2) ['', 'a', 'b c '] >>> ' a b c '.split(' ', 3) ['', 'a', 'b', 'c '] >>> ' a b c '.split(' ', 4) ['', 'a', 'b', 'c', ''] >>> ' a b c '.split(' ', 5) ['', 'a', 'b', 'c', '']
Example 2¶
>>> '-a-b-c-'.split('-') ['', 'a', 'b', 'c', ''] >>> '-a-b-c-'.split('-', 1) ['', 'a-b-c-'] >>> '-a-b-c-'.split('-', 2) ['', 'a', 'b-c-'] >>> '-a-b-c-'.split('-', 3) ['', 'a', 'b', 'c-'] >>> '-a-b-c-'.split('-', 4) ['', 'a', 'b', 'c', ''] >>> '-a-b-c-'.split('-', 5) ['', 'a', 'b', 'c', '']
Example 3¶
>>> '----a---b--c-'.split('-') ['', '', '', '', 'a', '', '', 'b', '', 'c', ''] >>> '----a---b--c-'.split('-', 1) ['', '---a---b--c-'] >>> '----a---b--c-'.split('-', 2) ['', '', '--a---b--c-'] >>> '----a---b--c-'.split('-', 3) ['', '', '', '-a---b--c-'] >>> '----a---b--c-'.split('-', 4) ['', '', '', '', 'a---b--c-'] >>> '----a---b--c-'.split('-', 5) ['', '', '', '', 'a', '--b--c-'] >>> '----a---b--c-'.split('-', 6) ['', '', '', '', 'a', '', '-b--c-']
See Also¶
rsplit() for version that splits from the right
© Copyright 2015, Jakub Przywóski. Revision 9a3b94e7 .
Versions latest Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
Python String split() Method
Split a string into a list where each word is a list item:
txt = «welcome to the jungle»
Definition and Usage
The split() method splits a string into a list.
You can specify the separator, default separator is any whitespace.
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax
Parameter Values
Parameter | Description |
---|---|
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is «all occurrences» |
More Examples
Example
Split the string, using comma, followed by a space, as a separator:
txt = «hello, my name is Peter, I am 26 years old»
Example
Use a hash character as a separator:
Example
Split the string into a list with max 2 items:
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split(«#», 1)
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Изучаем метод split Python 3
Метод split в Python разбивает строку на части, используя специальный разделитель, и возвращает эти части в виде списка.
Метод split в питоне — синтаксис
str.split([разделитель [, maxsplit]])
Функция split Python — параметры
В методе split() используется не более двух параметров:
- разделитель ( необязательный параметр ) – строка разбивается на части с помощью указанного символа. Если разделитель не задан, то любая пробельная строка ( пробел, новая строка и т.д. ) считается разделителем;
- maxsplit ( необязательный параметр ) определяет максимальное количество частей.
Если в maxsplit имеет значение -1 то, что количество разбиений строки неограниченно.
Возвращаемое значение в split()
Метод Python split string разбивает строку с помощью указанного спецсимвола и возвращает список подстрок.
Как работает метод split Python 3 — пример
text= 'Love thy neighbor' # разделяем строку print(text.split()) grocery = 'Milk, Chicken, Bread' # разделяем запятой print(grocery.split(', ')) # разделяем двоеточием print(grocery.split(':'))
В результате выполнения данной программы с Python split методом вы увидите:
['Love', 'thy', 'neighbor'] ['Milk', 'Chicken', 'Bread'] ['Milk, Chicken, Bread']
Выполнение split() при заданном maxsplit — пример
grocery = 'Milk, Chicken, Bread, Butter' # maxsplit: 2 print(grocery.split(', ', 2)) # maxsplit: 1 print(grocery.split(', ', 1)) # maxsplit: 5 print(grocery.split(', ', 5)) # maxsplit: 0 print(grocery.split(', ', 0))
На выходе получаем результат выполнения метода split Python 3 :
['Milk', 'Chicken', 'Bread, Butter'] ['Milk', 'Chicken, Bread, Butter'] ['Milk', 'Chicken', 'Bread', 'Butter'] ['Milk, Chicken, Bread, Butter']
При заданном параметре maxsplit максимальное количество элементов в списке равно maxsplit+1 .
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.
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.
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.
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.
Conclusion
- The split() function in python is used to split a particular string into smaller strings by breaking the main string using the given specifier.
- It returns a list containing the split strings.
- It works for a string and takes 2 parameters, specifier and maximum count for split.
- Finally the list returned can be iterated over and all the split strings can be easily accessed in that list.