Formatted string to object

bruno at modulix onurb at xiludom.gro
Mon Jun 19 12:49:15 EDT 2006


Tim Chase wrote:
>> Can you use strings or %s strings like in the above or
>>
>> aaa = 'string'
>> aaa.%s() % 'upper'
>>
>> Somehow?
> 
> 
> Looks like you want to play with the eval() function.
> 
>>>> aaa = 'hello'
>>>> result = eval("aaa.%s()" % 'upper')
>>>> result
> 'HELLO'

Using eval() or exec should be really avoided whenever possible IMHO.
This one is best done with getattr(obj, attribute_name [,default]), ie:

>>> aaa = "string"
>>> getattr(aaa, 'upper')()
'STRING'
>>>


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list