简体   繁体   中英

Python - How do I turn String into Array

I have a 2d array [['s1.modernroleplay.net', '27016', '27015'], ['s2.modernroleplay.net', '27019', '27018'], ['s3.modernroleplay.net', '27022', '27021']]

This 2d Array is stored in MySQL, once taking it out of MySQL it is in a String format.

How can I convert this string, back into an array?

you can try:

import json

my_string = "[['s1.modernroleplay.net', '27016', '27015'], ['s2.modernroleplay.net', '27019', '27018'], ['s3.modernroleplay.net', '27022', '27021']]".replace("'", '"')

my_array = json.loads(f'{{"array" : {my_string}}}')['array']
print(my_array)

# output
# [['s1.modernroleplay.net', '27016', '27015'],
#  ['s2.modernroleplay.net', '27019', '27018'],
#  ['s3.modernroleplay.net', '27022', '27021']]

You can use ast

for example:

import ast

print(ast.literal_eval("[['s1.modernroleplay.net', '27016', '27015'], ['s2.modernroleplay.net', '27019', '27018'], ['s3.modernroleplay.net', '27022', '27021']]"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM