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]'.
Use slices to list ranges other than "[]".
>>> b = list(map(int, a[1:-1].split(", ")))
>>> print(b)
[1, 2, 3, 4] # <class 'list'>
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.
>>> 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'>
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!
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