-2

i want to have this form

[(1, 'A'), (1, 'd'), (1, 'e'), (1, 'l'), (1, ' '), (1, 'a'), (1, 'n'), (1, 'd'), (1, ' '), (1, 'm'), (1, 'o'), (1, 'h'), (1, 'a'), (2, 'm'), (1, 'e'), (1, 'd')]

but i got this

["(1, 'A')", "(1, 'd')", "(1, 'e')", "(1, 'l')", "(1, ' ')", "(1, 'a')", "(1, 'n')", "(1, 'd')", "(1, ' ')", "(1, 'm')", "(1, 'o')", "(1, 'h')", "(1, 'a')", "(2, 'm')", "(1, 'e')", "(1, 'd')"]

and here is my code

def openRLEFile():
    file = askopenfile(parent=root,title='Select a File')
    global filename
    filename = file.name
    content = [x.strip('\n') for x in file]
    tDecompressed = decodeRLE(content)
    text.delete(0.0,END)
    text.insert(0.0,tDecompressed)
    file.close()
Kir Chou
  • 2,980
  • 1
  • 36
  • 48

2 Answers2

1

While eval() as proposed by 宏杰李 works conveniently, it is often not recommended to use it for security purpose.

Instead you could process manually:

def my_process(x):
    x = x[1:-1] # get rid of brackets
    x = x.split(", ")
    return (int(x[0]), x[1])

then use:

content = [my_process(x.strip('\n')) for x in file]
Julien
  • 13,986
  • 5
  • 29
  • 53
-2

use eval to convert str to python tuple, like this:

eval("(1, ' ')")

out:

(1, ' ')

in you case:

content = [eval(x.strip('\n')) for x in file]

to make the code safety, recommend use ast.literal_eval

import ast
content = [ast.literal_eval(x.strip('\n')) for x in file]
宏杰李
  • 11,820
  • 2
  • 28
  • 35
  • 2
    I would caution against doing `eval` on the contents of files and would recommend anyone dropping in here from the internet of the future takes a very serious look at whether or not they want to blindly execute whatever may be represented as code in a file. – erewok Dec 11 '16 at 06:17
  • @erewok sorry can you explain why it's dangerous ? – Mohammed Ehab Mohammed Dec 11 '16 at 06:20
  • the file could contain virus code, and `eval` will then execute it... – Julien Dec 11 '16 at 06:22
  • `eval` takes a string and evaluates it is as code. Your program is processing data from a file. If there is malicious code in the file, you would be would running it by running `eval` on it. – erewok Dec 11 '16 at 06:23