0

I need to convert a list into a string and then do the reverse process. Note that one script will convert List->String and another script will convert String->List, so store the list in a variable is not a solution. Use split(', ') or similar is not a solution either in all cases. So, as a challange I invite you to do the conversion in the following example:

l = ['ab,.cd\'ac"', b'\x80', '\r\nHi, !', b'\x01']
str_l = str(l)

I have tried one thing that worked: using exec() built-in function but people says is not a good practice, so I invite you to give me another alternative. Also I am having problems using exec() inside a function but that's another question that you can check -> Using exec() inside a function Python 3

Community
  • 1
  • 1
Martin DLF
  • 231
  • 2
  • 3
  • 7

1 Answers1

0

This should work:

str_l = ("|").join(l)

Which gives you your first string. Then do:

l_2 = str_l.split("|")

Which gives you your second list.

enter image description here

Kyle Coventry
  • 555
  • 3
  • 9
  • It fails for two reasons, first: str_l = ("|").join(l) Raises TypeError: > Traceback (most recent call last): File "", line 1, in > > str_l = ("|").join(l) TypeError: sequence item 1: expected str instance, bytes found And the second one is that my lists contains all kind of symbols so you just can't use "|" in the real example. Thank you anyway! – Martin DLF Jan 21 '15 at 18:28
  • Worked for me. Added a picture in my solution. – Kyle Coventry Jan 21 '15 at 18:31
  • I'm using python 3.4 and I get TypeError in line 2. Also, your final list if different to initial list (bytes were replaced by strings) and as I said above, you just can't use | because the real example contains all kind of symbols. Thanks again! – Martin DLF Jan 21 '15 at 18:38