How to Split a String Based on a Delimiter in Python
In this article, we show how to split a string in Python based on any type of delimiter such as a comma or semicolon.
A comma is probably the most common delimiter used to separate a string, but any can be used such as a semicolon or white space.
So to split a string in Python, we use the split() function. Inside of this split function in quotes (single or double), we put the delimiter that we want to break the string up.
This is shown below.
If you were to run this code you would get the following output shown below.
Now if you want to get the value of each of the individual of the string
broken up by the delimiter, in this case a comma, the code would be as shown below.
This gives us the following output shown below.
Technically, you could use code, such as the following shown below.
This would give us the following output.
However, this is not the best way of doing it, because if you are receiving input from a user and you don't know how many items they are going to enter,
you're not going to know how many elements there will be. Therefore, it is best practice to use a for loop in order to loop through all of the elements that are broken up
in the original string by the split() function.