B.Joelene B.Joelene - 4 years ago 199
Python Question

Convert a string literal into a list of strings

I have

letters = ["'FD', 'DD', 'CB', 'AA', 'CB', 'BA', 'BB', 'FD', 'CC', 'CB', 'BA', 'DC', 'CB', 'CC', 'FD', 'CC', 'CB', 'FF'"]


and I want to split the first and last " " and create this list

letters = ['FD', 'DD', 'CB', 'AA', 'CB', 'BA', 'BB', 'FD', 'CC', 'CB', 'BA', 'DC', 'CB', 'CC', 'FD', 'CC', 'CB', 'FF']


Here is my attempt, unfortunately is seems to give me the same list again:

a=["'FD', 'DD', 'CB', 'AA', 'CB', 'BA', 'BB', 'FD', 'CC', 'CB', 'BA', 'DC', 'CB', 'CC', 'FD', 'CC', 'CB', 'FF'"]
a="".join(a)
a=a.replace('"'," " )
print a
n=[]
n.append(a)

Answer Source

You could try the following:

string = letters[0]
listInDesiredFormat = string.replace('\'', '').split(', ')

This takes the string which is the first element of the list, replaces all single quotes and then splits on the comma to obtain a list of strings

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download