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:
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
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: