In this blog we are going to learn how to split string in python. splitting a raw string in python programming is an important technique to process raw string data.

To split a string into tokens we use python inbuilt function split().

Syntax of split() function

string.split(separator, max_num)

separator is the delimiter and max is the number. split() method split the string into max_num of times according to separator. The split() function returns list of strings.

Let us understand it by simple example.

#!/usr/bin/python

rawData = "I am learning python seriously"
data = rawData.split()

print(data)

#print data list
for str in data:
    print(str)

bosch@bosch-Inspiron-N5050:~$ python main.py
[‘I’, ‘am’, ‘learning’, ‘python’, ‘seriously’]
I
am
learning
python
seriously

Note:

If we do not provide any arguments to split() method, then the default value of separator is white space and default value of max_num is unlimited.

Now lets we have another string data “I love; python programming; because it is easy to learn”

If we need to split this string into

I love

python programming

because it is easy to learn

Then the separator value would be ‘;’ , let us see example code

#!/usr/bin/python

rawData = "I love;python programming;because it is easy to learn"
data = rawData.split(';')

#print data list
for str in data:
    print(str)

 

The output of the above program would be

I love
python programming
because it is easy to learn

How to split string into limited number of splits

Suppose we have a string “I love python programming; because it is easy to learn; machine learning with python is easy; too good”  and we want to split this string into 2 parts only with separator ‘;’

Here is the way

str =  "I love python programming; because it is easy to learn; machine learning with python is easy; too good"
splited_str = str.split(';',2)

#print splited_str
for string in splited_str:
    print(string)

output:

I love python programming
 because it is easy to learn
 machine learning with python is easy; too good

 

Learn free course for python

https://www.hackerrank.com/challenges/python-string-split-and-join/problem




Related Contents to follow