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 the ast module:
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
Example:
>>> import ast
>>> ast.literal_eval("(255, 0, 0)")
(255, 0, 0)
>>>
Regarding pygame, note that the Color class can also take the name of a color as string:
>>> import pygame
>>> pygame.color.Color('RED')
(255, 0, 0, 255)
>>>
so maybe you could generally simplify your code.
Also, you should not name your dict Color, since there's already the Color class in pygame and that will only lead to confusion.