Python: Convert a string to a list
Python List: Exercise - 56 with Solution
Write a Python program to 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:
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.
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://w3resource.com/python-exercises/list/python-data-type-list-exercise-56.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics