The Python split() function breaks up a string at the specified separator (space, comma, etc) and returns a list of Strings. You can do it with use the python inbuilt split function. In this tutorial, you will learn, how to split a string by space, character, delimiter, comma into a list and Python split string and get the first element.
Syntax of split() Function :
If no separator (space, coma etc) is defined then whitespace will be used by default.
str.split([separator [, maxsplit]])
Parameters
- separator: The is a delimiter. The string splits at this specified separator. It is not provided, then any white space is a separator.
- maxsplit: It is a number, which tells us to split the string into.
- a maximum number of times. If it is not provided, then there is no limit.
Return Value split() function
The split() breaks the string at the separator and returns a list of strings.
Python split() Stings Example :
Here is an example of, how the split() function can use in python. Good to see the use of every Python split() method example for learning and interview perspective.
Splits at space
str1 = 'Split this string in Python' print(str1.split())
Output : [‘Split’, ‘this’, ‘string’, ‘in’, ‘Python’]
Splits at comma ‘,’
str1 = 'Split, Python string' print(str1.split(','))
Output : [‘Split’, ‘ Python string’]
Splits at character
str1 = 'Split, Python string' print(str1.split('t'))
Output : [‘Spli’, ‘, Py’, ‘hon s’, ‘ring’]
maxsplit: 0
0 Maxsplit means no split.
str1 = 'Split, Python , string , eyehunt' print(str1.split(',', 0))
Output : [‘Split, Python , string , eyehunt’]
maxsplit: 1
Will split up to 1
str1 = 'Split, Python , string , eyehunt' print(str1.split(',', 1))
Output : [‘Split’, ‘ Python , string , eyehunt’]
Get the first element after Split String :
You can add index numbers to get specific elements, see this example get the first element of the string after a split. Index starts from 0, you can get any element just pass another number. Where max limit is length – 1
str1 = 'Split, Python , string , eyehunt' print(str1.split(',')[0])
Output: Split
Get the Last element after Split String :
You have to do get the length of string and then length - 1
, because the indexing starts from 0.
str1 = 'Split Python string eyehunt' str_s = str1.split(' ') print(str_s[len(str_s) - 1])
Output : eyehunt
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All Examples of Python Split() Function are in Python 3, so it may change its different from python 2 or upgraded versions.