How to convert / restore a string with [] in python

Thing you want to do

I would like to convert a string defined as'[1,2,3,4]' to a list.

>>> a = [1, 2, 3, 4]
>>> a = str(a)
>>> print(a)
[1, 2, 3, 4]
>>> print(type(a))
<class 'str'>

It is difficult to understand from the standard output, but the programmatically it is the character string'[1, 2, 3, 4]'.

environment

Method 1: Use slices

Use slices to list ranges other than "[]".

>>> b = list(map(int, a[1:-1].split(", ")))
>>> print(b)
[1, 2, 3, 4]  # <class 'list'>

Method 2: Use eval ()

eval () is a function that executes the code in a string. For example, the following execution is possible.

>>> eval("print('hello')")
hello

You can see that the print statement in the string is being executed. If you use eval (), it will be treated as an expression, not as a string.

Conversion using eval

>>> a = [1, 2, 3, 4]
>>> a = str(a)
>>> print(a)
[1, 2, 3, 4]  # <class 'str'>

>>> b = eval(a)
>>> print(b)
[1, 2, 3, 4]  # <class 'list'>

Summary

The above two methods are summarized. It may not be used very often, but it was a good opportunity to learn the difference between str and repr. Please, try it!

Postscript

Although eval () was introduced in Method 2, it was pointed out that there is a security problem. (Thank you!) There is no problem with this method, but it seems that ast.literal_eval () is recommended because it can execute arbitrary scripts when accepting input from the outside.

Reference: [Why is it dangerous to use the eval function in web forms etc.? ](Https://ja.stackoverflow.com/questions/61989/eval%E9%96%A2%E6%95%B0%E3%82%92web%E3%83%95%E3%82%A9%E3% 83% BC% E3% 83% A0% E3% 81% AA% E3% 81% A9% E3% 81% A7% E4% BD% BF% E3% 81% 86% E3% 81% A8% E3% 81% AA% E3% 81% 9C% E5% 8D% B1% E9% 99% BA% E3% 81% AA% E3% 81% AE% E3% 81% 8B)

Recommended Posts

How to convert / restore a string with [] in python
How to embed a variable in a python string
[Python] How to expand variables in a character string
How to convert an array to a dictionary with Python [Application]
[Python] How to convert a 2D list to a 1D list
How to work with BigQuery in Python
[Python] How to invert a character string
How to get a stacktrace in python
Convert to a string while outputting standard output with Python subprocess
How to make a string into an array or an array into a string in Python
[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to output a character string in a Print statement
How to get a string from a command line argument in python
How to create a heatmap with an arbitrary domain in Python
How to read a CSV file with Python 2/3
[REAPER] How to play with Reascript in Python
How to clear tuples in a list (Python)
Convert PDFs to images in bulk with Python
How to create a JSON file in Python
How to notify a Discord channel in Python
How to use tkinter with python in pyenv
[Python] How to draw a histogram in Matplotlib
[python] Convert date to string
Note: [Python3] Convert datetime to a string in any format you like
How to write a string when there are multiple lines in python
[Introduction to Python] How to write a character string with the format function
How to develop in Python
Parse a JSON string written to a file in Python
I want to embed a variable in a Python string
[Python] How to draw a line graph with Matplotlib
How to write string concatenation in multiple lines in Python
How to do hash calculation with salt in Python
Explain in detail how to make sounds with python
How to convert a class object to a dictionary with SQLAlchemy
How to run tests in bulk with Python unittest
How to convert floating point numbers to binary numbers in Python
Convert the image in .zip to PDF with Python
How to convert JSON file to CSV file with Python Pandas
I want to work with a robot in python.
[Python] Created a method to convert radix in 1 second
[Python] How to create a 2D histogram with Matplotlib
How to execute a command using subprocess in Python
[Python] How to draw a scatter plot with Matplotlib
How to drop Google Docs in one folder in a .txt file with python
[Tentative] How to convert a character string to Shift_jis with kivy-ios Memo kivy v1.8.0
How to get a list of files in the same directory with python
How to write a Python class
[Python] How to do PCA in Python
Python: How to use async with
Convert markdown to PDF in Python
How to collect images in Python
How to use SQLite in Python
Convert list to DataFrame with python
How to convert 0.5 to 1056964608 in one shot
How to get started with Python
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
6 ways to string objects in Python
How to use FTP with Python
Convert a string to an image