How to Convert Between Comma-Separated Strings and Lists in Python
This guide covers two common and related tasks:
- Converting a comma-separated string (or a string with other separators) into a list.
- Converting a list (of strings or numbers) into a comma-separated string.
We'll explore the most efficient and Pythonic methods, using str.split()
, str.join()
, list comprehensions, and map()
.
Converting a Comma-Separated String to a List
Basic Splitting with str.split()
The str.split()
method is the primary tool for converting a delimited string into a list:
my_str = 'tutorial,reference,com'
my_list = my_str.split(',') # Split on commas
print(my_list) # Output: ['tutorial', 'reference', 'com']
- The
my_str.split(',')
splits the string by commas and constructs a list of substrings.
Handling Different Separators
str.split()
can handle any separator string, not just commas:
my_str = 'tutorial reference com'
my_list = my_str.split() # Split on any whitespace, by not providing an argument
print(my_list) # Output: ['tutorial', 'reference', 'com']
my_str = 'tutorial, reference, com'
my_list = my_str.split(', ') # Split on comma and space
print(my_list) # Output: ['tutorial', 'reference', 'com']
- The
split()
method takes an optionalseparator
parameter. If no value is provided, it defaults to splitting on whitespace.
Handling Leading/Trailing Separators
If your string starts or ends with the delimiter, split()
will create empty strings in the list. To remove those:
my_str = ',tutorial,reference,com,'
my_list = [item for item in my_str.split(',') if item]
print(my_list) # Output: ['tutorial', 'reference', 'com']
- The
if item
condition in the list comprehension filters out empty strings. - Another, less readable way, to do this is to use
filter
:my_list = list(filter(None, my_str.split(',')))
Converting to a List of Integers
If your string contains numbers, convert them to integers after splitting:
my_str = '1,2,3,4,5'
my_list = [int(item) for item in my_str.split(',')]
print(my_list) # Output: [1, 2, 3, 4, 5]
#OR
my_list = list(map(int, my_str.split(',')))
print(my_list) # Output: [1, 2, 3, 4, 5]
- List Comprehension (recommended):
[int(item) for item in ...]
converts each substring to an integer. map()
:map(int, ...)
applies theint()
function to each element. This returns amap
object, which is then converted to a list usinglist()
. The list comprehension is generally preferred for readability.- If your string also contains other characters, and you only want to keep the numbers, you can check with
isdigit()
andint()
to convert the string to a number.
Converting a List to a Comma-Separated String
Joining a List of Strings
The str.join()
method is the most efficient and Pythonic way to join a list of strings into a single string:
list_of_strings = ['tutorial', 'reference', 'com']
my_str = ','.join(list_of_strings) # Join with commas
print(my_str) # Output: tutorial,reference,com
my_str_space = ' '.join(list_of_strings) # Join with space
print(my_str_space) # Output: tutorial reference com
- The method takes a list of strings as an argument, and joins them using a separator.
Joining a List of Integers
If your list contains numbers, you first need to convert them to strings:
list_of_integers = [1, 3, 5, 7]
# Using a generator expression (more efficient)
my_str = ','.join(str(item) for item in list_of_integers)
print(my_str) # Output: 1,3,5,7
# OR, using map (less readable, but also works):
my_str = ','.join(map(str, list_of_integers))
print(my_str) # Output: 1,3,5,7
- Generator Expression:
(str(item) for item in list_of_integers)
converts each integer to a string as it's being used byjoin()
. This is memory-efficient. map(str, list_of_integers)
: Appliesstr()
to each integer, creating amap
object (an iterator). This is less readable than the generator expression.