I was wondering what the simplest way is to convert a string
list like the following to a list
:
x = u'[ "A","B","C" , " D"]'
Even in case user puts spaces in between the commas, and spaces inside of the quotes. I need to handle that as well to:
x = ["A", "B", "C", "D"]
in Python.
I know I can strip spaces with strip()
and split()
using the split operator and check for non alphabets. But the code was getting very kludgy. Is there a quick function that I'm not aware of?
So, following all the answers I decided to time the most common methods:
So in the end regex wins!
There is a quick solution:
Unwanted whitespaces in the list elements may be removed in this way:
with
numpy
this is working a very simple waygives
To further complete @Ryan 's answer using json, one very convenient function to convert unicode is the one posted here: https://stackoverflow.com/a/13105359/7599285
ex with double or single quotes:
Assuming that all your inputs are lists and that the double quotes in the input actually don't matter, this can be done with a simple regexp replace. It is a bit perl-y but works like a charm. Note also that the output is now a list of unicode strings, you didn't specify that you needed that, but it seems to make sense given unicode input.
The junkers variable contains a compiled regexp (for speed) of all characters we don't want, using ] as a character required some backslash trickery. The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.
Note that this also removes spaces from inside entries u'["oh no"]' ---> [u'ohno']. If this is not what you wanted, the regexp needs to be souped up a bit.
Let's assume your string is t_vector = [34, 54, 52, 23] and you want to convert this into a list. You can use the below 2 steps:
t_vector contains the list.