How To Use Python Split on strings

Guys, Have you ever stopped at somewhere while processing the larger text data in python?

Mostly for those who do the natural language processing projects, they need to deal with the larger text data i.e., splitting strings into lists so on.

And, we can do this very easily with the Python string split() function.It simply splits the given string as you would like to divide it.

What it exactly does?

1.If you give any operator to split function then it will split the given string based on that operator.Operators can be anything like (“,”),(“a”)..etc

2.If you didn’t give any operator to that string then it will split the string into list by spaces

Also Read :   Python Write To File | How To Write Files In Python

Let’s see the examples for detail understanding 🙂

Python String Split Examples

1.Python String split into a List

#python string split into list

string = "hello world, this is prathap."
outputList = string.split()
print(outputList)

#output -> ['hello', 'world,', 'this', 'is', 'prathap.']

In the above code, I have assigned some text to a string variable.Then, I applied the split function on the string variable with no operators.

So, It returns a list of words which are separated by spaces in the string.

2.Python String Split into a List by Characters

#python string split into list by charecters

#seperated by comma into a list
string1 = "hello world, this is prathap."
outputList1 = string1.split(',')
print(outputList1) #output -> ['hello world', ' this is prathap.']

#seperated by an alphabet "L"  into a list
string2 = "hello world, this is prathap."
outputList2 = string2.split('l')
print(outputList2) #output -> ['he', '', 'o wor', 'd, this is prathap.']

#seperated by an alphabet "i" into a List
string3 = "hello world, this is prathap."
outputList3 = string3.split("i")
print(outputList3) #output -> ['hello world, th', 's ', 's prathap.']

If you read the documentation/comments in the above code, you can find the differences among them.

Also Read :   How To Connect Python To MYSQL Database Tutorial

First string was separated by a comma. Here, we have only one comma  in the string that means it will divide  the string into two list elements

Second String was separated by an alphabet L.So, we have 4 elements in our list

Third string was separated by an alphabet I.So, we have 3 elements in our list.

Guys Please comment your feedback doubts or queries below and join our group 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *