3

I need cast a list to a string and get back the string to a list. There's a python way to make this behavior?

l1 = ['aa','bb','cc']
s = str(l1)
l2 = cast_string_to_list(s)
print l2
"['aa','bb','cc']"
3
  • what are you trying to achieve with this ? casting in python is a weird word... Aug 30, 2011 at 15:40
  • I know "casting" in python is weird, but I need a word to explain the problem, may be "transform" is a more happy word :)
    – lctr30
    Aug 30, 2011 at 15:49
  • 3
    "serialize" is probably the word you're looking for
    – Luke404
    Aug 30, 2011 at 16:50

6 Answers 6

10

Use a serialization library like json:

import json

l1 = ['aa','bb','cc']
s = json.dumps(l1)
l2 = json.loads(s)

print s
print l1 == l2
5
  • One reason I'd recommend pickle over json is that pickle can handle many more classes of objects. For instance, import datetime; json.dumps(datetime.datetime.now()) won't work unless you define a helper function that knows how to serialize datetime objects. Aug 30, 2011 at 16:07
  • 1
    check this using dicts: m1 = {1:2}; d = json.dumps(m1); m2 = json.loads(d); m2[1]
    – lctr30
    Aug 30, 2011 at 16:26
  • 3
    @lctr30, The json module does not try to form an implicit schema for your data like pickle does, so to use it, the user programmer needs to sit down and define how the data will be stored. This is a feature, not a bug. Implicit schema-ization introduces problems, among them that it is impossible to be completely correct. The effort spent defining how to represent your state using JSON or another well-defined serialization format is the time it takes to be correct. Aug 30, 2011 at 16:48
  • json.loads() doesn't create an ordered list. Does anybody know a solution? @KirkStrauser @lctr30 @MikeGraham @JochenRitzel
    – sunwarr10r
    Dec 7, 2016 at 17:45
  • JSON is defined as unordered. It's possible that Python 3.6 will order it as parsed since it's switched to using ordered dicts by default, but this is purely speculative. Dec 7, 2016 at 23:30
4

In somewhat recent Python versions, you can use ast.literal_eval, which is essentially eval without the security problems. You could also try to do the parsing yourself (or use Python's parser and then replicate the logic of literal_eval before evaling the AST), although both are wheel reinventions and the latter is likely much less robust as soon as it gets to string literals.

Why do you need it anyway? There are serialization formats that can handle conversion to and from string of various data structures (not just lists of strings) for you, such as Pickle (somewhat insecure itself, read the notice in the docs), JSON, YAML, and probably more. They're much more robust and appropriate for such tasks.

3

You can use ast module:

import ast

l1 = ['aa','bb','cc']
s = str(l1)
ast.literal_eval(s)
>>> ['aa','bb','cc']

Or something like this - but i don't like it too much:

l1 = ['aa','bb','cc']
s = str(l1)
l2 = [x.strip(" '") for x in s.strip('[]').split(',')]
6
  • I wonder about a time when everybody who want to down-vote will need to specify a comment with reason of this. Aug 30, 2011 at 16:41
  • The first solution is wrong-headed, and though it can be said to address the very narrow question, does not help OP at all. The second has the same criticisms, but is also silently incorrect. Aug 30, 2011 at 16:54
  • @Mike - both solutions do the trick using his input data sample - is it not so? Aug 30, 2011 at 17:41
  • That doesn't make them useful, helpful, or correct for any meaningful problem domain. Remember, answering a literal question is not always most valuable—we should always strive to post answers which truly help the asker. Aug 30, 2011 at 18:42
  • 1
    Ok - thanx, i see. Please bear with me - because it still cause some doubts in my head, but it doesn't seem i can resolve them here - since users voting here depends from many things here on SO. I saw quite a lot of answers here where people said that ast is quite good and acceptable or atleast better than simple eval, someone told that string parsing is also good even in such a case and so on. I even can't find any words about serializing/deserializing data in OP question - because in such i case i would also recomend pickle - but seems that all of this doesn't matter at all Aug 30, 2011 at 19:26
1

The pickle module is probably what you're looking for:

import pickle
l1 = ['aa','bb','cc']
s = pickle.dumps(l1)
l2 = pickle.loads(s)
print l2
5
  • 4
    Note that pickle should be avoided when possible due to its lack of security, portability, and correctness. Aug 30, 2011 at 16:05
  • @Mike Graham, I think that's terrible advice. Sure, you don't want to unpickle data received from untrusted sources. But if your goal is persisting data to a local file, or a database, or to transmit it between two trusted services, why on Earth wouldn't you? Within its boundaries of appropriate use, pickle is tremendously convenient and powerful. Don't avoid such useful mechanisms just because it's possible to use them inappropriately. Aug 30, 2011 at 16:15
  • 3
    @Kirk, Pickle has tons of problems and nothing to endear it to us. Pickle is insecure. Unpickling can execute arbitrary Python code--there's no reason to open this door cautiously when you can keep it closed altogether. Pickle is not portable. Pickle does not allow you to define a data-oriented representation of your state and can only really be read by Python. Pickle is incorrect. Pickle can fail quietly, saving blatantly wrong data or data that cannot be restored. These sorts of drawbacks are totally not what I'm looking for in a serialization protocol. Aug 30, 2011 at 16:34
  • @Mike, Pickle isn't insecure if you're not fetching your data from untrusted sources. Pickle doesn't need to be portable if you're not interacting with non-Python sources, or if you're just persisting your data for short term. Pickle seems to be correct in that it throws PickleErrors when it can't pickle something. Pickle has great coverage of Python datatypes (much better than JSON). Basically, it's a poor choice for things like accepting serialized data from external clients. It's an excellent choice for when you have control over both endpoints of the transaction. Aug 30, 2011 at 16:54
  • 3
    Pickled objects frequently don't even work on other environments. For example, one can pickle an object that on one OS is a WindowsBloBar, and on another is UnixBloBar. Unpickling makes the wrong object, etc. Overall pickle is fragile, using it at the wrong time in the wrong way produces terrible consequences, and it's generally best avoided except in an extremely narrow set of circumstances, which in all likelihood do not count the OP's circumstance among them. Aug 30, 2011 at 19:02
0

This is an aside for this question, but I was looking for a way to cast a non-delimited string to a single-element list and realized I could assign with square brackets. Knowing this behavior in Python helped me think through string-to-list and back problems.

l1 = 'aa bb cc'
print(type(l1))
l2 = [l1] 
print(type(l2))
print(l2)
print(l2[0])
1
-4

If you are always working with a list, then the following kind of thing should work just fine. Beware, it will not cast ints to ints and such; they will always be string items in the list.

l1 = ['aa','bb','cc']
s = str(l1)

l2 = s[1:-1].split(',')

print l2
['aa', 'bb', 'cc']

You probably want to check the boundaries of the string and such to check that it's long enough for that array stuff too...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.