简体   繁体   English

Python - 将字符串转换为列表

[英]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? (类似这样:['Arcer.exe','Launcher.exe','Document.txt'])现在我怎样才能将字符串转换回列表?

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. 我建议使用json模块。

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) 要发送列表,您可以将str(flist)更改为json.dumps(flist)然后在另一端使用flist = json.loads(string)重新加载列表

You can use literal_eval from ast module: 您可以使用ast模块中的literal_eval

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: 如果您不想使用ast模块,另一种方法是从字符串中删除括号,然后将其拆分为每个逗号,字符如下:

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 . 首先, 永远不要命名变量liststring 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. 您应该避免使用Python变量的字符串表示,因为读取和写入它们不会有效。 But, if you have no other option, you can use ast.literal_eval : 但是,如果您没有其他选项,则可以使用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'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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