Hi I want change a string into an list like:
'[KEYTYPE.FWPROD2KEY, KEYTYPE.FWPROD2KEY, DOWNLOADMODE.FWTOFW, False, DEPLOYMODE.DEPLOY]'
into
[KEYTYPE.FWPROD2KEY, KEYTYPE.FWPROD2KEY, DOWNLOADMODE.FWTOFW, False, DEPLOYMODE.DEPLOY]
Hi I want change a string into an list like:
'[KEYTYPE.FWPROD2KEY, KEYTYPE.FWPROD2KEY, DOWNLOADMODE.FWTOFW, False, DEPLOYMODE.DEPLOY]'
into
[KEYTYPE.FWPROD2KEY, KEYTYPE.FWPROD2KEY, DOWNLOADMODE.FWTOFW, False, DEPLOYMODE.DEPLOY]
Here’s a simple function to deal with this, using split and replace:
Assuming that ‘stringlist’ is your string’d list...
def transformlist(stringlist):
stringlist = stringlist.split(sep=',')
stringlist[0] = stringlist[0].replace('[','')
stringlist[-1] = stringlist[-1].replace(']','')
return stringlist
You could use .split() then getattr() and ast.literal_eval()
import ast
s = '[KEYTYPE.FWPROD2KEY, KEYTYPE.FWPROD2KEY, DOWNLOADMODE.FWTOFW, False, DEPLOYMODE.DEPLOY]'
def get_val(value):
values = value.split('.')
if values[0] in locals: return getattr(getattr(locals, value), values[1])
if values[0] in globals: return getattr(getattr(globals, value), values[1])
try: return ast.literal_eval(value)
except: return value
#slice the string to get rid of the brackets
#and .replace to remove all spaces
data = [get_val(val) for val in s[1:-1].replace(' ', '').split(',')]
This is probably the safe way of doing this.
Probably the most succinct way is use the re
module to split and remove symbols from the string, then recombine the strings back into a list
data structure:
import re
s = '[KEYTYPE.FWPROD2KEY, KEYTYPE.FWPROD2KEY, DOWNLOADMODE.FWTOFW, False, DEPLOYMODE.DEPLOY]'
l_str = ''.join(re.split(', [ ]', s))
l = eval(l_str)
or a one-liner:
l = eval(''.join(re.split(', [ ]', s)))
To Arya's points in the comment since I don't have those variables defined I can't test it, but you should then be able to verify the result is of type list
:
>>> print(type(l))
<type 'list'>