简体   繁体   中英

Python – Convert string to list

I am working at a "cloud server" for myself. I have a tool to list files which are on the server.

flist = os.listdir("C:/Server")
conn.send(bytes("str(flist), "UTF-8"))        

This sends a list to the client, the client converts it to a string. (something like this: [' Arcer.exe', 'Launcher.exe', 'Document.txt']) Now how can I convert the string back into a list?

string = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
list = []
list = string.convert  #pseudo method
print(list[0]) #Arcer.exe
print(list[1]) #Launcher.exe

I would recommend using the json module.

To send the list you can change str(flist) to json.dumps(flist) then on the other end you can reload the list using flist = json.loads(string)

You can use literal_eval from ast module:

from ast import literal_eval
string = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
newList = literal_eval(string)
print(newList)

Output:

[' Arcer.exe', 'Launcher.exe', 'Document.txt']

If you do not want to use the ast module, another way of doing it is to remove the brackets from your string and then split it in every comma , character as follows:

string = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
newList = string[1:-1].replace("'","").split(",")
print(newList)

This will give you the same output as the above:

[' Arcer.exe', ' Launcher.exe', ' Document.txt']

First, never name variables list or string . The first is the name of a built-in class, the second is a module in the standard library.

You should avoid using string representations of Python variables, since reading and writing them are not going to be efficient. But, if you have no other option, you can use ast.literal_eval :

from ast import literal_eval

x = "[' Arcer.exe', 'Launcher.exe', 'Document.txt']"
y = literal_eval(x)

print(y, type(y))

[' Arcer.exe', 'Launcher.exe', 'Document.txt'] <class 'list'>

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