So I am making a dice game, and one thing I wanted to do was have a high scores list as a text file. Currently I have a function that can change the file if the score of the player is in the top 5. This currently works with an array, which gets sent to the text file as a string. I want to be able to read this and convert it into an array again so I can compare values if I want to try and beat the score for another time, yet I cant seem to get it back into an array. This is what I get from using .split(","): ['[37', ' 0', ' 0', ' 0', ' 0]'], and this is what is inside the text file: [37, 0, 0, 0, 0]. Keep in mind I am in year 9, so I do not mind if the code is long, I just want it to work.
-
Can you upload your original string?? – nacho Jul 09 '22 at 11:37
-
3You can use the `literal_eval` function from the `ast` module to evaluate the array as a Python list: `from ast import literal_eval` `literal_eval("[37, 0, 0, 0, 0]")` => `[37, 0, 0, 0, 0]` – Lecdi Jul 09 '22 at 11:38
-
You can try with json.loads too – nacho Jul 09 '22 at 11:40
1 Answers
There are many ways to do this depending upon what the goal of your learning is.
If you're not allowed to use library functions you can do the following:
Currently you're saying:
>>> scores = "[37, 0, 0, 0, 0]"
>>> scores.split(",")
['[37', ' 0', ' 0', ' 0', ' 0]']
The problems here are you still have the square brackets included in the first and last strings, and the spaces between the elements have been retained. Also, you want integers as the result rather than strings.
A couple of things to help:
First strip the []
from the ends before you do the split:
>>> scores.strip('[]')
'37, 0, 0, 0, 0'
Then call split with comma and space as separator:
>>> scores.strip('[]').split(', ')
['37', '0', '0', '0', '0']
Now we want to apply the int
conversion to each string. You can do this with map
(you might have done mappings in math):
>>> values = ['37', '0', '0', '0', '0']
>>> list(map(int, values))
[37, 0, 0, 0, 0]
Alternatively you could build your list using a comprehension. This is a way of saying what each element in a list should be based upon some other sequence. So, it's a mapping really:
>>> [int(value) for value in values]
[37, 0, 0, 0, 0]
It's a bit longer than the map
way, but I like comprehensions and use them a lot. They're more flexible than map
as you can filter and don't need a function to apply.
As others have commented there are libraries which could help you, but understanding what I've shown you will be useful to your general python skills.
Good luck!

- 23,859
- 5
- 60
- 99