将字符串转换为元组 [英] Convert a string to a tuple

查看:952
本文介绍了将字符串转换为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从文件中读取了一些元组数据.元组为字符串形式,例如Color["RED"] = '(255,0,0)'.如何将这些字符串转换为实际的元组?

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?

我想像这样在PyGame中使用这些数据:

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

推荐答案

您可以使用ast literal_eval 模块:

You could use the literal_eval of the ast module:

ast. literal_eval ( node_or_string )

安全地评估包含Python文字或容器显示的表达式节点或Unicode或Latin-1编码的字符串.提供的字符串或节点只能由以下Python文字结构组成:字符串,数字,元组,列表,字典,布尔值和无.

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也可以采用名称颜色为字符串:


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.

此外,您不应该为您的dict Color命名,因为pygame中已经存在Color类,这只会引起混乱.

Also, you should not name your dict Color, since there's already the Color class in pygame and that will only lead to confusion.

这篇关于将字符串转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆