Split a string in Python

These days I am developing a project in Python for W3Api and API standardization. A very simple but useful thing that came up for me was having to split a string of Python of elements separated by commas to be able to assign a series of values.

Let’s get to work. The first thing we have would be the chain. In this case I have created a string type variable that contains a set of elements separated by commas. They are a set of means of transportation.

list = "plane, car, motorcycle, boat, submarine"

To be able to separate it we are going to use the .split() method which divides the string based on a separator and if we do not say anything it divides it for each blank space that is found. If not, we should pass as a parameter the value by which we want to divide the string.

words = list.split()

The .split() method returns us a list of elements with the division of the string. That is why we will use a for...in statement to traverse the list. and the .print() method to show it on the screen.

for word in words:
    print (word.strip())

When I show it on the console we will see that we have divided our words but that there are a series of aspects that we have to improve. The first is that the commas appear. We solve this by indicating that the separator of the .split() method is not the white space, but the comma.

words = list.split(",")

And the second aspect is that white spaces now appear. Therefore, every time we go through the list we will eliminate the white spaces using the .strip() method.

for word in words:
    print (word.strip())

In this way we will have already managed to divide a string into Python from the commas that are found. I hope that even though it is a simple article you find it useful.