Python split() Function

The split() function in Python is used when we need to split a string into a list. For example:

str = "codes cracker dot com"
print(str.split())

The output is:

['codes', 'cracker', 'dot', 'com']

By default - The split() converts a string into a list where each words of string, becomes elements of list. For example:

str = "codes cracker dot com"

str = str.split()
print(type(str))

for x in str:
    print(x)

The output produced by this program, demonstrating the split() function in Python, is shown in the snapshot given below:

python split function

Python split() Function Syntax

The syntax of split() function in Python, is:

string.split(separator, maxsplit)

where separator refers to a separator that is used to separate the string, where each separated part becomes the element of list. The maxsplit parameter is used to specify the number of splits to perform.

Note: Both the parameters, that are separator and maxsplit are optional.

Note: The default value of separator is any whitespace, whereas the default value of maxsplit is -1, and -1 means to split all occurrences of separator.

If 3 given to maxsplit, then the first three phrases separated by separator got split, rest of all phrases becomes the last element of list.

Python split() Function Example

Here is an example of split() function in Python:

x = "Sun-05-Dec-2021"
x = x.split("-", 2)
print(x)

x = "Hey, Python is fun!, Isn't it?"
x = x.split(",")
print(x)

x = "Hey, Python is fun!, Isn't it?"
x = x.split()
print(x)

The output is:

['Sun', '05', 'Dec-2021']
['Hey', ' Python is fun!', " Isn't it?"]
['Hey,', 'Python', 'is', 'fun!,', "Isn't", 'it?']

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!