w3resource

Python: Convert a string to a list

Python List: Exercise - 56 with Solution

Convert String to List

Write a Python program to convert a string to a list.

Python: Convert a string to a list

Sample Solution:

Python Code:

# Import the 'ast' module, which provides a safe way to evaluate Python literals
import ast

# Define a string 'color' containing a Python list as a string
color = "['Red', 'Green', 'White']"

# Use the 'ast.literal_eval' function to safely evaluate the string as a Python literal expression
# This function ensures that the string is treated as a valid Python literal, in this case, a list
# Print the result, which is the actual list created from the string
print(ast.literal_eval(color)) 

Sample Output:

['Red', 'Green', 'White']

Flowchart:

Flowchart: Convert a string to a list

Python Code Editor:

Previous: Write a Python program to remove key values pairs from a list of dictionaries.
Next: Write a Python program to check if all items of a given list of strings is equal to a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-56.php