Home > Backend Development > Python Tutorial > How to Convert a Comma-Delimited String into a List in Python?

How to Convert a Comma-Delimited String into a List in Python?

Linda Hamilton
Release: 2024-10-20 13:38:29
Original
653 people have browsed it

How to Convert a Comma-Delimited String into a List in Python?

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>
Copy after login

This code generates the following output:

['A', 'B', 'C', 'D', 'E']
Copy after login

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>
Copy after login

You can also append additional elements to the list using the append() method:

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

print(my_list)</code>
Copy after login

This results in an extended list:

['A', 'B', 'C', 'D', 'E', 'F']
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template