Home >Backend Development >Python Tutorial >How to Convert Comma-Delimited Strings to Lists in Python?

How to Convert Comma-Delimited Strings to Lists in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 13:37:29319browse

How to Convert Comma-Delimited Strings to Lists in Python?

Converting 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.

Problem Statement

Convert a comma-delimited string into a Python list, transforming values like "A,B,C,D,E" into ['A', 'B', 'C', 'D', 'E'].

Solution Using str.split

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>

Converting to Tuples

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>

Appending to an Existing List

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn