Python Split | String split() in Python

In Python, there is a built-in string method called split() that splits a string into a list of substrings. It takes two optional parameters, separator, and maxsplit.

Specifies the separator to use when splitting the string. By default, any whitespace characters (spaces, tabs, and newlines) is a separator. Specifies how many splits to do using maxsplit. The default value is -1, which is “all occurrences”.

Syntax: string.split(separator, maxsplit)

Examples of Split() in Python

my_string = "Hello world! Howdy"
split_string = my_string.split() 
print(split_string)
Output: [‘Hello’, ‘world!’, ‘Howdy’]

As you can see, we haven’t provided any separator or maxsplit parameters, by default, the split() function has chosen space as a separator and it split till the last point.

Split the string, using comma, followed by a space, as a separator:

my_string = "Hello, world!, Howdy"
split_string = my_string.split(', ') 
print(split_string)
Output: [‘Hello’, ‘world!’, ‘Howdy’]
my_string = "abc%def%ghi%jkl"
split_string = my_string.split('%') 
print(split_string)
Output: [‘abc’, ‘def’, ‘ghi’, ‘jkl’]

Using both the delimiter:

my_string = "abc%def%ghi%jkl"
split_string = my_string.split('%', 1) 
print(split_string)
Output: [‘abc’, ‘def%ghi%jkl’]

As you can see, we have provided the separator as # and maxsplit as 1. So the split() function has splited the string upto first # separator.

Try all these codes on our online python compiler

Related:

Python Basics
List, Set, Tuple, and Dictionary in Python
Python Reverse List items
Python Round() Function
Python Multiline comment
Power in Python | Python pow()
Python range() Function
Square Root in Python
Python for i in range
Python Exception Handling