0

I'm currently trying to load a .txt file that has the following inside the file:

['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10]

When I load the file, read the information on the file and store it on a variable named content:

    self.file_name = filedialog.askopenfilename()
    if self.file_name is None:
        return
    with open(self.file_name) as f:
        content = f.read().splitlines()

When I print out content:

    print(content)

I get the following output:

["['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10]"]

The problem is that there's quotation marks when it prints. Could there be anyway to get rid of the ""? The reason is because since it's a two dimensonal list and print([0][1]) I get the result of ' instead of chest

cahuizar
  • 35
  • 7
  • You can replace strings as follows: `a_str.replace('"','')`. Not sure if this is what you are after. Please confirm. – Marcin Dec 08 '14 at 23:01
  • @Marcin I cant seem to figure out where `a_str.replace('"','')` would go in my code.. Does it go after the line `content =....`? – cahuizar Dec 08 '14 at 23:09
  • And this one? `content[0].replace('"','')` – Marcin Dec 08 '14 at 23:11

2 Answers2

1

If your content contains syntax representing correct python literal code, you can parse it directly into python data:

content = ["['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10]"]

import ast
a_tuple = ast.literal_eval(content[0])
print(a_tuple)

Results in a tupple containing the parased string:

(['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['decline'], [1], [1], [10])
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • Where are you getting `ast.` from? When I do this I get the following error: `NameError: name 'ast' is not defined` – cahuizar Dec 08 '14 at 23:14
  • ast is standard python module. Import it `import ast`. Link is [here](https://docs.python.org/3.4/library/ast.html). – Marcin Dec 08 '14 at 23:19
0

print(content[0])

The content variable is holding an array of a single string. When you did print(content[0][1]), you printed the second character of the string. When printing a string, the outer quotes are not shown, but when printing an array, the outer quotes are shown (so you can see where each string begins and ends).

Havvy
  • 1,471
  • 14
  • 27
  • When I do this, I get the result of `['Chest', ['bench', 'incline'], [2, 1], [10, 10], [10, 20, 10]], 'Chest', ['cola'], [1], [1], [10]` since it's a two dimensional list. I dont get the result of just `Chest` – cahuizar Dec 08 '14 at 23:07
  • It's a string that looks like a two dimensional list. It's not a two dimensional list. You'd need to transform it into one first. – Havvy Dec 08 '14 at 23:12
  • @Havyy I see what you mean, but how exactly would I transform it into a two dimensional? – cahuizar Dec 08 '14 at 23:15