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

How to Convert Comma-Delimited Strings to Python Lists?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 13:43:29922browse

How to Convert Comma-Delimited Strings to Python Lists?

Transforming Comma-Delimited Strings to Python Lists

Given a string containing a series of comma-separated values, it is desirable to convert it into a Python list. This transformation aids in further data analysis and manipulation.

To achieve this, leverage the str.split method:

<code class="python">my_string = 'A,B,C,D,E'
my_list = my_string.split(",")
print(my_list)</code>

This yields a list of strings: ['A', 'B', 'C', 'D', 'E']. If a tuple is preferred, simply enclose the list in parentheses:

<code class="python">print(tuple(my_list))</code>

For appending to an existing list, utilize the .append method:

<code class="python">my_list.append('F')
print(my_list)</code>

This appends 'F' to the list, resulting in ['A', 'B', 'C', 'D', 'E', 'F'].

The above is the detailed content of How to Convert Comma-Delimited Strings to Python Lists?. 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