How to convert strings to lists in python?

I’m creating a document organization program using lists, and I converted the list to an encoded string. When I decode the string, it has the same text as the list, but it’s a string! How can I convert this:

"['a', 'list', 'of', 'strings']"

to this:

['a', 'list', 'of', 'strings']
1 Like

Welcome to the community! Why do you have a string that resembles a list? Perhaps there is a better way to write your code.
Now I think I can help with this.

var1 = "['a', 'list', 'of', 'strings']" # Your string
var1 = var1.strip("[]").replace("'", "").split(", ") # This converts
# it to a list
print(var1) # Print list

Or make a function for ease of use:

var1 = "['a', 'list', 'of', 'strings']" # Your string list
def toList(string): # Function to use
  return string.strip("[]").replace("'", "").split(", ") # This
  # sends the list back to the program. You can assign it to
  # a variable like so "var2 = toList(var1)"
print(toList(var1)) # Print list

The code worked! Thanks! I was encoding and decoding a list, and the module turned it into a string.

It doesn’t work with a list of lists, though. Anything that can help with that?

It needs to be a lot more complex to do that. I’ll see what I can do.

2 Likes

I can probably change the characters the list uses, as files in the list use () instead of .

1 Like

That won’t change anything. Leave it as is. I’m working on seeing if there’s an effective way to do this.

2 Likes

Okay, thanks. I’ll try to find a better way to encode and decode the list while you’re focused on that.

1 Like

I believe you can use the json library for this.

Load from a file:

import json

with open('myFile') as file:
    data = json.load(file)

Load from string:

import json

string_list = "[1, 2, 3, 4, 5]"
data = json.loads(string_list)

It works recursively meaning you can have lists inside of lists and you can also use this to load a json file or string into a python dictionary. Plus, it can tell the difference between a number and a string so “12” is a string and 12 is a number.

As for encoding, you can still use the same library like this:

data = ["a", "b", "c", ["hi", "idk"], 3, 4]

string_data = json.dumps(data)
3 Likes

I couldn’t get that to work but I can’t get my code to work either so I’m done here. Sorry I couldn’t be of more help.

1 Like

It’s fine. I’ll think of a better encryption system. Thanks for trying!

1 Like

Works! Thanks for the reply!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.