How to convert a string with comma-delimited items to a list in Python?

How to convert a string with comma-delimited items to a list in Python?

How do you convert a string into a list in Python?

For example, if the string is like text = “a,b,c”, after the conversion, text == [‘a’, ‘b’, ‘c’] and hopefully text[0] == ‘a’, text[1] == ‘b’.

How can you achieve this using string to array python?

Hi,

Can you please try using the split() method:

text = "a,b,c"
text_list = text.split(',')
print(text_list)

This approach uses the split() method to split the string into a list based on the comma delimiter. It works well for simple cases like this one.

You can also use list comprehension:

text = "a,b,c"
text_list = [item for item in text.split(',')]
print(text_list)

In this solution, the split() method is used in combination with a list comprehension to convert the comma-separated string into a list. This is an alternative to the previous method with more flexibility if you want to add additional processing inside the comprehension.

Hi,

Other than the above approach, you can also using the map() function:

text = "a,b,c"
text_list = list(map(str, text.split(',')))
print(text_list)

In this approach, the map() function is used to apply the str function to each item in the list returned by split(). This ensures each element is properly converted to a string, although it’s not strictly necessary in this case, as split() already returns strings.