python字符串转化为元组,将字符串转换为元组

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值