Menu Close

Python String split() Method

Python String split

In this article, you will learn about the Python string split() method which is used to split the string. split function in Python only works with string because it is a string built-in function.

Here we will understand the split() string method using some various example
so that you can understand better.
In the previous tutorial, we have seen the Python string rfind() method to find the highest index of the specified string.

Python String split() Method

Python split() string method is used to split the string using separator as delimiter and return a list. If any separator not specified, Then whitespace treats as a separator.

split in python accepts an additional parameter that is maxsplit which represents how many split you want to do.

Syntax

The syntax of Python string split method is:-

string.split(sep, maxsplit)

Parameters

split in Python accept two optinal parameters.

  • sep:- Optional. Specify the separator to use when split the string. If any separator not specifies, Then whitespace treats as a separator.
  • maxsplit:- Optional. Specify a number to parameter maxsplit that represents how many split you want to do.

Return Value

split in python return the list which contains splitted string.

Python string split() example:

Here we will take some examples to understand split function in Python.

Example 1:

#split in Python without any parameter.
a = 'Programming Funda is a educational site'
result = a.split()
print(result)

Output:

[‘Programming’, ‘Funda’, ‘is’, ‘a’, ‘educational’, ‘site’]

Example 2:

#split in Python with separator parameter.
a = 'Programming, Funda, is, a, educational, site'
result = a.split(sep = ', ')
print(result)

Output:

[‘Programming’, ‘Funda’, ‘is’, ‘a’, ‘educational’, ‘site’]

Example 3:

#split in Python with separator and maxsplit parameter.
a = 'Programming, Funda, is, a, educational, site'
result = a.split(sep = ', ', maxsplit=3)
print(result)

Output:

[‘Programming’, ‘Funda’, ‘is’, ‘a, educational, site’]

Example 4:

#Iterate over a sequence (list return by split in Python)
a = 'Programming, Funda, is, a, educational, site'
result = a.split(sep = ', ')
for i in result:
	print(i)

Output:

Programming
Funda
is
a
educational
site

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Conclusion

In this tutorial, you have learned about the python string split method along with various examples.
split function in Python is mostly used by Python programmers. You can perform lots of operations using this function.

I hope this tutorial will help you. if you like this article please share it with your friends who want to learn Python program from scratch to advanced.

Other string methods

For more information:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts

Leave a Reply