How to Split String by Commas in Python

In this simple tutorial, we will see how to split a string into a list of strings using the most common delimiter: the comma.

#what we have string = "value_1, value_2, value_3" #what we want output = ["value_1", "value_2", "value_3"]
Code language: Python (python)

Use the split() method to split a string by commas

Python comes with a built-in method for strings: split(). It returns a list of the words in the string, using the sep as the delimiter string. Let’s see a simple example:

print('1,2,3'.split(',')) #['1', '2', '3']
Code language: PHP (php)

Some relevant information for this method:

  • You can indicate whatever you want as a delimiter, even if we used a comma in this case
  • If you don’t indicate the separator, Python will use spaces
  • The result is always a list of strings. If you want to convert texts to integer (for example), you need to use a list comprehension
print([int(element) for element in '1,2,3'.split(',')])
Code language: Python (python)

Output:

[1, 2, 3]
Code language: Python (python)

You also have the option to fix the number of splits by using the maxsplit arguments. It prevents Python from finding the maximum number of splits based on your separator.

print('1,2,3'.split(',')) print('1,2,3'.split(',', maxsplit=1))
Code language: Python (python)

Output:

['1', '2', '3'] ['1', '2,3']
Code language: JSON / JSON with Comments (json)

Use the re module for more complex splits

Even if we want to split our string by commas, we can have some cases where the regular split() method is not enough. Let’s consider a case where we have this string:

'1,2,,,,3'
Code language: Python (python)

If we wanted to get non-null values of the separated version of this string, we cannot use the approach we described above:

print('1,2,,,,3'.split(','))
Code language: Python (python)

Output:

['1', '2', '', '', '', '3']
Code language: JSON / JSON with Comments (json)

We could use a list comprehension to get rid of the empty strings, but it’s not ideal:

print([element for element in '1,2,,,,3'.split(',') if element != ''])
Code language: CSS (css)

Output:

['1', '2', '3']
Code language: JSON / JSON with Comments (json)

A better approach is to leverage the re module ro create a more flexible seperator definition, using a regular expression

import re print(re.split(',+','1,2,3'))
Code language: Python (python)

Output:

['1', '2', '3']
Code language: Python (python)

Using a regular expression, we can let Python know that our strings are separated by one or more (the + sign) and we can therefore generate our output without having to create a list comprehension.

Leave a Reply

Your email address will not be published. Required fields are marked *