将字符串转换为元组
Convert a string to a tuple
我从文件中读取了一些元组数据。元组为字符串形式,例如 Color["RED"] = '(255,0,0)'
。如何将这些字符串转换为实际的元组?
我想在 PyGame 中像这样使用此数据:
gameDisplay.fill(Color["RED"])
# but it doesn't have the right data right now:
gameDisplay.fill('(255,0,0)')
您可以使用 ast.literal_eval()
-
例子-
import ast
ast.literal_eval('(255,0,0)')
>>> (255, 0, 0)
你的情况 -
gameDisplay.fill(ast.literal_eval(Color["RED"]))
请注意,ast.literal_eval 将计算表达式(即字符串)和 return 结果。
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.
您可以使用 ast
模块的 literal_eval
:
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.
示例:
>>> import ast
>>> ast.literal_eval("(255, 0, 0)")
(255, 0, 0)
>>>
关于pygame,请注意Color
class也可以将颜色名称作为字符串:
>>> import pygame
>>> pygame.color.Color('RED')
(255, 0, 0, 255)
>>>
所以也许您可以大体上简化您的代码。
此外,您不应该将 dict
命名为 Color
,因为 pygame 中已经存在 Color
class,这只会导致混淆.
其他答案使用 ast
模块,但同样的事情可以使用内置函数 eval
.
>>> mystring = '(255,0,0)'
>>> eval(mystring)
(255,0,0)
我从文件中读取了一些元组数据。元组为字符串形式,例如 Color["RED"] = '(255,0,0)'
。如何将这些字符串转换为实际的元组?
我想在 PyGame 中像这样使用此数据:
gameDisplay.fill(Color["RED"])
# but it doesn't have the right data right now:
gameDisplay.fill('(255,0,0)')
您可以使用 ast.literal_eval()
-
例子-
import ast
ast.literal_eval('(255,0,0)')
>>> (255, 0, 0)
你的情况 -
gameDisplay.fill(ast.literal_eval(Color["RED"]))
请注意,ast.literal_eval 将计算表达式(即字符串)和 return 结果。
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.
您可以使用 ast
模块的 literal_eval
:
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.
示例:
>>> import ast
>>> ast.literal_eval("(255, 0, 0)")
(255, 0, 0)
>>>
关于pygame,请注意Color
class也可以将颜色名称作为字符串:
>>> import pygame
>>> pygame.color.Color('RED')
(255, 0, 0, 255)
>>>
所以也许您可以大体上简化您的代码。
此外,您不应该将 dict
命名为 Color
,因为 pygame 中已经存在 Color
class,这只会导致混淆.
其他答案使用 ast
模块,但同样的事情可以使用内置函数 eval
.
>>> mystring = '(255,0,0)'
>>> eval(mystring)
(255,0,0)