python - Convert a string to a tuple -
this question has answer here:
- parse tuple string? 3 answers
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
Post a Comment