Python Split() Function | Split String Example

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.

Python Split() Function | Split String Example in python

Syntax of split() Function :

If no separator (space, coma etc) is defined then whitespace will be used by default.

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 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

Output : [‘Split’, ‘this’, ‘string’, ‘in’, ‘Python’]

Splits at comma  ‘,’

Output :  [‘Split’, ‘ Python string’]

Splits at character

Output : [‘Spli’, ‘, Py’, ‘hon s’, ‘ring’]

maxsplit: 0

0 Maxsplit means no split.

Output : [‘Split, Python , string , eyehunt’]

maxsplit: 1

Will split up to 1

Output : [‘Split’, ‘ Python , string , eyehunt’]

Get the first element after Split String :

You can add index number 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 

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.

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.6

Python 3.7

All Examples of Python Split() Function are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.