How to Convert a Comma Separated String to a List in Python?

Estimated read time 1 min read

To convert a comma-separated string to a list in Python, you can use the split() method. Here’s an example:

def string_to_list(csv_string):
    # Remove leading and trailing whitespace
    csv_string = csv_string.strip()
    # Split the string using the comma delimiter
    csv_list = csv_string.split(',')
    return csv_list

# Example usage
csv_string = 'apple,banana,orange'
result = string_to_list(csv_string)

In this example, we define a function string_to_list that takes a comma-separated string as input. First, we remove any leading and trailing whitespace from the string using the strip() method.

Then, we split the string into a list using the split(',') method. The split() method separates the string based on the comma delimiter and returns a list of substrings.

Finally, we return the csv_list, which will contain the elements from the comma-separated string as a Python list.

You can replace 'apple,banana,orange' in the example with your own comma-separated string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply