One example where you need this is if you process a CSV file. CSV files typically use a delimiter like a comma (,) or a semicolon (;) to separate entries.
If you want to read a CSV file (or any other file) in Python, you can find an explanation in the Python read and write files lesson. In this lesson, we’ll focus on how to split strings.
We use the
split() method by specifying the string, followed by
.split() , and a separator between the parentheses. If you don’t specify a separator, the default separator is a space.
Let’s try to split a string which uses a comma as the delimiter:
split() method converts our string into a list, using the comma as the separator, and returns a list with three strings. Let’s try one more example:
This time I specified a semicolon as the separator. Once again, we get a list of three separate strings. Since we have a list, we can access any of the items on the list. Let’s assign the output of the
split() method to a new variable:
In the code above, I stored the output of the
split() method in a list variable named “csv_line”. Now it’s easy to access any of the list items and use them in our code.
You have now learned how to split strings in Python. I hope you enjoyed this lesson. If you have any questions feel free to leave a comment!