Python String Split() Method

The Python string split() method lets us split a string into a list.





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:

The 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.

Conclusion

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!


Forum Replies

  1. Hello Pradyumna

    If the variable csv_line is a string, then the output of that variable in the window on the right will be of the form “R1,IOS-XE,192.168.1.1”.

    If the variable csv_line is a list, then the output of that variable in the window on the right will be of the form [‘R1’, ‘IOS-XE’, ‘192.168.1.1’].

    Notice in the following screenshot, initially, the output of csv_line is with quotes, and separated by commas. After it is converted, it appears in square brackets, with each item of the list in single quotes, and separated by commas.

    https://cdn-forum.netwo

    ... Continue reading in our forum

Ask a question or join the discussion by visiting our Community Forum