Home >Backend Development >Python Tutorial >How to Convert Comma-Delimited Strings to Lists in Python?
When working with textual data, it's often necessary to extract specific values from strings. Comma-separated values (CSVs) are a common format for storing multiple values in a single string. To leverage CSVs effectively, you need to be able to convert them into more manageable data structures, such as lists.
Convert a comma-delimited string into a Python list, transforming values like "A,B,C,D,E" into ['A', 'B', 'C', 'D', 'E'].
The str.split method provides a convenient way to split a string by a given delimiter, in this case, a comma. The resulting list contains individual elements that were originally separated by commas.
<code class="python">mStr = 'A,B,C,D,E' mList = mStr.split(",") print(mList) # Output: ['A', 'B', 'C', 'D', 'E']</code>
If you wish to create a tuple instead of a list, simply apply the tuple() function to the split result:
<code class="python">myTuple = tuple(mList) print(myTuple) # Output: ('A', 'B', 'C', 'D', 'E')</code>
To append comma-separated values to an existing list, use the append() method:
<code class="python">myList = ['A', 'B', 'C'] myList.append('D,E') print(myList) # Output: ['A', 'B', 'C', 'D,E']</code>
Alternatively, you can use the extend() method to append each individual value:
<code class="python">myList.extend(['D', 'E']) print(myList) # Output: ['A', 'B', 'C', 'D', 'E']</code>
Now you have the tools to efficiently convert comma-delimited strings into Python lists, tuples, or extend existing lists with new values.
The above is the detailed content of How to Convert Comma-Delimited Strings to Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!