-6

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]
BENY
  • 258,262
  • 17
  • 121
  • 165
bob
  • 25
  • 7
  • 3
    Is `KEYTYPE.FWPROD2KEY` supposed to be a string? Some constant looked up elsewhere? The end result you're describing isn't a legal `list` literal, so you need to be more clear here. A complete [MCVE] would be ideal (not only making it clear what you want, but showing some effort). – ShadowRanger Jan 17 '19 at 01:13
  • If security is not an issue, you can just do eval(list_string) - eval evaluates a string as code. – Arya Jan 17 '19 at 01:13
  • `eval` evaluates a string as python, but be very careful regarding the source of your strings as it can be a security issue. – Mike Robins Jan 17 '19 at 01:14
  • If security is not an issue, you can just do eval(list_string) - eval evaluates a string as code. – Arya Jan 17 '19 at 01:14
  • eval will only work here if KEYTYPE.FWPROD2KEY is some kind of defined value, and not a string. – Arya Jan 17 '19 at 01:21

3 Answers3

0

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
0

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.

Jab
  • 21,612
  • 20
  • 66
  • 111
0

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'>
davedwards
  • 7,011
  • 2
  • 15
  • 45