简体   繁体   中英

How to convert a list into a string and then convert it back in python?

I want to send a list through UDP/TCP, but since they support string list only, I need to convert the list into string and convert it back.

My list is like

['S1','S2','H1','C1','D8']

I know I can use

string_ = ''.join(list_) 

to convert it into string.

But how to convert it back?

Or there is another way I can use UDP/TCP to send a list?

Custom format would depend on the assumptions about the list items format, so json looks like the safest way to go:

>>> import json
>>> data = json.dumps(['S1','S2','H1','C1','D8'])
>>> data
'["S1", "S2", "H1", "C1", "D8"]'
>>> json.loads(data)
[u'S1', u'S2', u'H1', u'C1', u'D8']

Use a separator:

string_ = ';'.join(list_)

list_ = string_.split(';')

You need to make sure the separator character can't be within your string. If it is, you might need encoding.

Maybe you could append a separator between the list elements and use it calling split to get the list back.

EDIT:

As @Eric Fortin mentionned in his answer, the separator should be something that cannot be in your string. One possibility is -- as he suggested -- to use encoding. Another possiblity is to send elements one by one, but that would obviously increase the communication overhead.

Note that your separator may be a sequence, it does not need to be one single character.

str_list = separator.join(list_)
new_list = str_list.split(separator)

If you know the format of your list elements, you may even go without using separators!

str_list = "".join(list_)
re.split(reg_exp, str_list)

If you have python on both ends of network communication, you can use dumps and loads functions from pickle module design especially for serializing python objects:

import pickle

a = ['S1','S2','H1','C1','D8']
string_ = pickle.dumps(a)

...

a = pickle.loads(string_)

Otherwise solution proposed by @bereal is better one because there are json libraries for most programming languages. But it will demand some processing for data types not supported by json.

EDIT

As @bereal noticed there can be security problem with pickle because it's actually an executable language.

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