How to convert a string with comma-delimited items to a list in Python?
To convert a comma-separated string to a list, use the split()
:
If your string uses other characters or patterns as separators, set them as delimiter in split()
.
Dealing with whitespace in your string
split()
method is your friend when dealing with a comma-delimited string. However, beware of spaces before or after commas. For inconsistent white spaces, clean up your string first using strip()
or a list comprehension.
The above line of code ensures the items in your list are as clean as whistleblowers.
Accessing list elements and converting back to strings
Your newly-formed list allows access to individual elements via indexes. Remember, in Python, indexes count from 0, not 1 - just like the hours in a day!
Also, if you ever need to reunite your list items back into a string, join()
is your man (or method).
Complex strings that counterfeit lists
In cases where you have a string pretending to be a list (like "[1, 2, 3]"), use the ast.literal_eval
method. Acting as a bouncer, this method only processes Python literals, keeping you safe from malicious inputs.
Note: Ensure your string is dressed up exactly like a list before ast.literal_eval
can let it into the list club, or you will get a ValueError
.
Fine tuning: Delimiters, data types and nested structures
Delimiter options besides commas
Delimiters are not restricted to commas. A string might use semicolons, pipe characters, or even whitespace. Adjust split()
to your delimiter of choice accordingly.
Data type conversion
To split()
all items are just strings. To convert them to numerical types, enter the world of map function:
Preserving structure and types for complex strings
For strings containing nested structures like lists or tuples, the classic tool from the chest, ast.literal_eval
, comes to the rescue, maintaining the hierarchical structure.
Was this article helpful?