You were quite close, this is how I would've done it:
result = "('%s')" % "','".join(mylist)
Answer from Daniel Figueroa on Stack OverflowUse ast.literal_eval:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
import ast
input = "[[1,2,3],['c',4,'r']]"
output = ast.literal_eval(input)
output
=> [[1, 2, 3], ['c', 4, 'r']]
If you actually meant for c and r to just be the current values of the variables c and r rather than the literals 'c' and 'r', you'd need to use eval, which is rather unsafe, but otherwise works the same way.
if ast.literal_eval is not sufficient and c and r are meant to be non-trivial data objects that should be interpreted, you might consider using asteval (https://github.com/newville/asteval). It can handle evaluating python strings beyond literal strings, including its own symbol table, and avoiding many of the known exploits with using eval().
asteval works like a sand-boxed mini-interpreter with a simple, flat namespace. You would have to add values for c and r to the asteval interpreter, but an example might be:
from asteval import Interpreter
aeval = Interpreter()
aeval('c = 299792458.0') # speed of light?
aeval('r = c/(2*pi)') # radius of a circle of circumference c?
# note that pi and many other numpy
# symbols and functions are built in
input_string = "[[1,2,3],[c,4,r]]"
out = aeval(input_string)
print(out)
which will give
[[1, 2, 3], [299792458.0, 4, 47713451.59236942]]
Alternatively, you could have set c directly from Python with
aeval.symtable['c'] = 299792458.0
There are many known-to-be-unsafe things that asteval refuses to do, but there are also many things it can do that ast.literal_eval cannot. Of course, if you're accepting code from user input, you should be very careful.
Consider using literal_eval:
from ast import literal_eval
txt = ["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]
result = [literal_eval(i) for i in txt]
print(result)
Output:
[[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793], [21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]]
Edit:
Or eval(). Refer to Tim Biegeleisen's answer.
Using the eval() function along with a list comprehension we can try:
inp = ["[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793]", "[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]"]
output = [eval(x) for x in inp]
print(output)
This prints:
[
[21049090, 'AARTIIND22AUGFUT', 'AARTIIND', 850, 1793],
[21049346, 'ABB22AUGFUT', 'ABB', 250, 3329]
]
Try this:
y = [z[:6] for z in x]
This was the same as this:
y = [] # make the list
for z in x: # loop through the list
y.append(z[:6]) # add the first 6 letters of the string to y
Yes, there is. You can use the following list-comprehention.
newArray = [x[:6] for x in y]
Slicing has the following syntax: list[start:end:step]
Arguments:
start - starting integer where the slicing of the object starts
stop - integer until which the slicing takes place. The slicing stops at index stop - 1.
step - integer value which determines the increment between each index for slicing
Examples:
list[start:end] # get items from start to end-1
list[start:] # get items from start to the rest of the list
list[:end] # get items from the beginning to the end-1 ( WHAT YOU WANT )
list[:] # get a copy of the original list
if the start or end is -negative, it will count from the end
list[-1] # last item
list[-2:] # last two items
list[:-2] # everything except the last two items
list[::-1] # REVERSE the list
Demo:
let's say I have an array = ["doctorWho","Daleks","Cyborgs","Tardis","SonicSqrewDriver"]
and I want to get the first 3 items.
>>> array[:3] # 0, 1, 2 (.. then it stops)
['doctorWho', 'Daleks', 'Cyborgs']
(or I decided to reverse it):
>>> array[::-1]
['SonicSqrewDriver', 'Tardis', 'Cyborgs', 'Daleks', 'doctorWho']
(now i'd like to get the last item)
>>> array[-1]
'SonicSqrewDriver'
(or last 3 items)
>>> array[-3:]
['Cyborgs', 'Tardis', 'SonicSqrewDriver']
If the format is exactly the same you've provided, you'd better go with using re:
import re
file_info = ['{file:file1, directory:dir1}', '{file:file2, directory:directory2}']
pattern = re.compile(r'\w+:(\w+)')
for item in file_info:
print re.findall(pattern, item)
or, using string replace(), strip() and split() (a bit hackish and fragile):
file_info = ['{file:file1, directory:dir1}', '{file:file2, directory:directory2}']
for item in file_info:
item = item.strip('}{').replace('file:', '').replace('directory:', '')
print item.split(', ')
both code snippets print:
['file1', 'dir1']
['file2', 'directory2']
If the file_info items are just dumped json items (watch the double quotes), you can use json to load them into dictionaries:
import json
file_info = ['{"file":"file1", "directory":"dir1"}', '{"file":"file2", "directory":"directory2"}']
for item in file_info:
item = json.loads(item)
print item['file'], item['directory']
or, literal_eval():
from ast import literal_eval
file_info = ['{"file":"file1", "directory":"dir1"}', '{"file":"file2", "directory":"directory2"}']
for item in file_info:
item = literal_eval(item)
print item['file'], item['directory']
both code snippets print:
file1 dir1
file2 directory2
Hope that helps.
I would do:
import re
regx = re.compile('{\s*file\s*:\s*([^,\s]+)\s*'
','
'\s*directory\s*:\s*([^}\s]+)\s*}')
file_info = ['{file:C:\\samples\\123.exe, directory : C:\\}',
'{ file: C:\\samples\\345.exe,directory:C:\\}'
]
for item in file_info:
print '%r\n%s\n' % (item,
regx.search(item).groups())
result
'{file:C:\\samples\\123.exe, directory : C:\\}'
('C:\\samples\\123.exe', 'C:\\')
'{ file: C:\\samples\\345.exe,directory:C:\\}'
('C:\\samples\\345.exe', 'C:\\')