Convert a string to a tuple [duplicate]

被刻印的时光 ゝ 提交于 2019-12-17 21:22:06

问题


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

回答1:


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:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/31272772/convert-a-string-to-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!