This question already has an answer here:
- Parse a tuple from a string? 4 answers
I read some tuple data from a file. The tuples are in string form, for example Color["RED"] = '(255,0,0)'
. How can I convert these strings into actual tuples?
I want to use this data in PyGame like this:
gameDisplay.fill(Color["RED"])
# but it doesn't have the right data right now:
gameDisplay.fill('(255,0,0)')
You could use the
literal_eval
of theast
module:Example:
Regarding pygame, note that the
Color
class can also take the name of a color as string:so maybe you could generally simplify your code.
Also, you should not name your
dict
Color
, since there's already theColor
class in pygame and that will only lead to confusion.You can use
ast.literal_eval()
-Example -
In your case -
Please note, ast.literal_eval will evaluate the expression (which is the string) and return the result.
From documentation -
Other answers use the
ast
module, but the same thing can be done using the built-in functioneval
.See the docs for more info.