Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string formatting for python 2.5

In older version of python, 'str' object has no attribute 'format error will be resulted if i try to format string. params consists of something like [u'name', '12']. How to do the following in % string formatting?

def str(params):
    ......
    if params:
       msg_str = msg_str.format(*params)
like image 740
user1076881 Avatar asked Jul 28 '26 06:07

user1076881


1 Answers

Convert the list to a tuple and pass it as the format argument:

msg_str = msg_str % tuple(params)

Example:

>>> lst = [123, 456]
>>> 'foo %d bar %d' % tuple(lst)
'foo 123 bar 456'

Note, it must be a tuple, passing the list directly won't work:

>>> 'foo %d bar %d' % lst
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not list
like image 107
ThiefMaster Avatar answered Jul 29 '26 20:07

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!