Convert a string to a tuple [duplicate]

2019-01-20 19:34发布

This question already has an answer here:

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条回答
Juvenile、少年°
2楼-- · 2019-01-20 19:59

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-20 20:00

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.

查看更多
Juvenile、少年°
4楼-- · 2019-01-20 20:17

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.

查看更多
登录 后发表回答