Converting a Comma-Delimited String to a List in Python
How can I efficiently convert a string containing comma-separated values into a list? This conversion is a common task when working with data in Python.
Solution
Python's built-in str.split method provides an elegant solution for this task. It splits the string into a list of substrings based on a specified delimiter.
For a comma-delimited string, you can use the following code:
<code class="python">my_string = 'A,B,C,D,E' # Input string my_list = my_string.split(",") # Split the string into a list print(my_list)</code>
This code generates the following output:
['A', 'B', 'C', 'D', 'E']
Extension: Tuple Conversion and List Modification
If you need to convert the list to a tuple, simply use the tuple() function:
<code class="python">my_tuple = tuple(my_list) print(my_tuple)</code>
You can also append additional elements to the list using the append() method:
<code class="python">my_list.append('F') print(my_list)</code>
This results in an extended list:
['A', 'B', 'C', 'D', 'E', 'F']
The above is the detailed content of How to Convert a Comma-Delimited String into a List in Python?. For more information, please follow other related articles on the PHP Chinese website!