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 dictionary).
I tried many combinations with tuples and lists as formatters but without success, so I thought to ask here
I hope it's clear
[edit] OK, perhaps I wasn't clear enough
I have large text variable, like
s = ['a', 'b', ..., 'z']
x = """some text block
%s
onother text block
%s
... 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
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
A string is a sequence of unicode characters with quotation marks on either side of the sequence. A tuple is an ordered sequence of objects or characters separated by commas with parentheses on either side of the sequence.
Here, 'value' represents the data in any format like numbers, characters, or floating points. The types of string formatting applied in python programming are single formatter, multiple formatter, formatter with positional and keyword arguments, and index error.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With