This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 3 years ago.
I have a form that save lists as strings, I want to convert those strings to lists before save in DB.
I'm using python3 and Django.
The strings looks like:
'["MEX","MTY","GDL","BJX","QRO","PBC","TLC","CUN","EM","CUU"]'
what will be the most pythonic way to do that?
import json
json.loads('["MEX","MTY","GDL","BJX","QRO","PBC","TLC","CUN","EM","CUU"]')
Related
This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 5 months ago.
I have message which is a list and JSON in it. I managed to get JSON with raw decode. The problem is
string = "["a,b","b,c"]"
How can I convert that string into a list?
Use ast.literal_eval:
import ast
print(ast.literal_eval(string))
Since this is JSON, use the json module:
import json
print(json.loads(string))
string = "['a,b','b,c']"
print(eval(string))
This question already has answers here:
Python: Short way of creating a sequential list with a prefix
(3 answers)
Create a list of strings with consecutive numbers appended
(6 answers)
Appending the same string to a list of strings in Python
(12 answers)
Closed 7 months ago.
In Python how can I need to create a long list that I'm trying to avoid typing, the list looks lis this
brands = ['_1','_2','_3'... '_998']
I can create the list of numbers with a for loop, but I'm trying to use list comprehension for the characters which should be faster.
Thanks!
my list=["_" + str(i) for i in range(1,999)]
This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 11 months ago.
Say the string is like a = "['Hello', 'World']". After the conversion, a = ['Hello', 'World'] and the type is a list.
It's called expression evaluation. Read about Python's eval() and literal_eval().
Notice that it may be dangerous, so read the docs carefully.
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 3 years ago.
So I have string like this:
"UFFKTEWKW"
And I need to convert it to a list or tuple like this:
("UFF", "KTE", "WKW")
So every 3 letters from the string goes to separate element of list or tuple.
I can't use split() here because string doesn't have any delimiters. I don't wanna make some dummy for cycle for it. And I think there should be simple solution for it.
You can use this.
a="UFFKTEWKW"
out=tuple(a[i:i+3] for i in range(0,len(a),3))
# ('UFF', 'KTE', 'WKW')
This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 6 years ago.
I have a string, something like:
a = "[1, 2, 3]"
If there an easy way to convert it in to a list, without using .split(), join() etc.
Thanks for any replies.
use ast.literal_eval() it's safer than using eval
from ast import literal_eval
a = literal_eval("[1, 2, 3]")
print(a)