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:

Unlock This Lesson for Free - No Payment Required!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
2564 Sign Ups in the last 30 days

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