2

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)
strcat
5,6832 gold badges31 silver badges31 bronze badges
asked Apr 4, 2012 at 6:45
0

5 Answers 5

6

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
answered Apr 4, 2012 at 6:47
Sign up to request clarification or add additional context in comments.

Comments

3

In this simple case

>>> "{0} {1}.".format(*("Hello", "world"))
'Hello world.'

You can just change the msg_str to the old style

>>> "%s %s."%(("Hello", "world"))
'Hello world.'

However, format has quite a few capabilities beyond that. There is no straight forward way to translate this one

>>> "{1} {0}.".format(*("world", "Hello"))
'Hello world.'
answered Apr 4, 2012 at 7:07

Comments

2

Use the % operator to interpolate values into a format string

>>> "%(foo)s %(bar)d" % {'bar': 42, 'foo': "spam"}
'spam 42'
ThiefMaster
320k85 gold badges608 silver badges648 bronze badges
answered Apr 4, 2012 at 6:47

1 Comment

Please do not indent your non-code text. Syntax highlighting plain text doesn't make much sense.
1
msg_str = msg_str % tuple(params)
answered Apr 4, 2012 at 6:49

1 Comment

According to his question it's a list so he needs to convert it to a tuple.
0

Use string module available in Python 2.5

import string
tmp=string.Template("Hello ${name} !")
print tmp.safe_substitute(name="John")
answered Aug 24, 2014 at 14:39

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.