简体   繁体   中英

Reoccurring string-formatting within a list upon access in python

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.

It's better to use a function for this:

In [1]: from random import randint

In [2]: def func():
   ...:     return "The random number is: {0}".format(randint(0,10))
   ...: 

In [3]: func()
Out[3]: 'The random number is: 7'

In [4]: func()
Out[4]: 'The random number is: 2'

In [5]: func()
Out[5]: 'The random number is: 3'

You can create a class and override __str__ :

>>> from random import randint
>>> class Foo(object):
...     def __str__(self):
...        return "The random number is: {0}".format(randint(0,10))
... 
>>> a = [Foo()]
>>> print a[0]
The random number is: 8
>>> print a[0]
The random number is: 10
>>> print a[0]
The random number is: 5 

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:

a = ["The some sweet string: {func1}",
     "Another {func2} different string {func3}"]

for item in a:
   print item.format(func1=func1(),func2=func2(),func3=func3())

Obviously this isn't efficient (as you call functions when you don't necessarily need them ...), but it could work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM