Ghostly Ghostly - 1 year ago 57
Python Question

How to use list (or tuple) as String Formating value

Assume this variable:

s=['Python', 'rocks']
x = '%s %s' % (s[0], s[1])

Now I would like to substitute much longer list, and adding all list values separately, like s[0], s[1], ... s[n], does not seem right

Quote from documentation:

Given format % values... If format
requires a single argument, values may
be a single non-tuple object. [4]
Otherwise, values must be a tuple with
exactly the number of items specified
by the format string, or a single
mapping object (for example, a

I tried many combinations with tuples and lists as formaters but without success, so I thought to ask here

I hope it's clear

Thanks in advance

OK, perhaps I wasn't clear enought

I have large text variable, like

s = ['a', 'b', ..., 'z']

x = """some text block
onother text block
... end so on...
""" % (s[0], s[1], ... , s[26])

I would like to change
% (s[0], s[1], ... , s[26])
more compactly without entering every value by hand

Answer Source

You don't have to spell out all the indices:

s = ['language', 'Python', 'rocks']
some_text = "There is a %s called %s which %s."
x = some_text % tuple(s)

The number of items in s has to be the same as the number of insert points in the format string of course.

Since 2.6 you can also use the new format method, for example:

x = '{} {}'.format(*s)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download