0
votes

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)')
3

3 Answers

5
votes

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.

2
votes

You can use ast.literal_eval() -

Example -

import ast
ast.literal_eval('(255,0,0)')
>>> (255, 0, 0)

In your case -

gameDisplay.fill(ast.literal_eval(Color["RED"]))

Please note, ast.literal_eval will evaluate the expression (which is the string) and return the result.

From documentation -

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.

0
votes

Other answers use the ast module, but the same thing can be done using the built-in function eval.

>>> mystring = '(255,0,0)'
>>> eval(mystring)
(255,0,0)

See the docs for more info.