python - Convert a string to a tuple -


this question has answer here:

i read tuple data file. tuples in string form, example color["red"] = '(255,0,0)'. how can convert these strings actual tuples?

i want use data in pygame this:

gamedisplay.fill(color["red"]) # doesn't have right data right now: gamedisplay.fill('(255,0,0)') 

you use literal_eval of ast module:

ast.literal_eval(node_or_string)

safely evaluate expression node or unicode or latin-1 encoded string containing python literal or container display. string or node provided may consist of following python literal structures: strings, numbers, tuples, lists, dicts, booleans, , none.

example:

>>> import ast >>> ast.literal_eval("(255, 0, 0)") (255, 0, 0) >>> 

regarding pygame, note color class can take name of color string:

>>> import pygame >>> pygame.color.color('red') (255, 0, 0, 255) >>> 

so maybe simplify code.

also, should not name dict color, since there's color class in pygame , lead confusion.


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -