In python, is it possible to have a reoccurring string-formatting operation take place when an item in a list is accessed?
For example:
>>>from random import randint
>>>a = ["The random number is: {0}".format(randint(0,10))]
>>>print a[0]
The random number is: 3
>>>print a[0]
The random number is: 3
Obviously it’s obtaining a random integer, formatting the string and saving it in the list when the list is first defined. Performance hit aside, I’d like to know if it is possible to override this behavior.
I know if I were to see this question I would respond with something like “you’re doing it wrong” and would provide something similar to the below answer…
>>>a = ["The random number is: {0}"]
>>>print a[0].format(randint(0,10))
But lets assume that’s not a solution for this question. I’d really like for the formatting to be defined and take place in the list itself (if possible).
Another example:
a = ["The some sweet string: {0}".format(someFunction),
"Another {0} different string {1}".format(someFunctionTwo, someFunctionThree)]
Where someFunction* provides a “random” result upon each call.
I know its a bit of a stretch and I may have to rely on the methods provided already ( thanks for your feedback ) but, I figured I’d give it a shot.
Thanks again.
You can create a class and override
__str__:But you’re right, my first inclination is to say that you’re probably doing it wrong…
Here’s another idea — keep your lists with format strings in them:
Obviously this isn’t efficient (as you call functions when you don’t necessarily need them …), but it could work.