Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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

like image 610
Ghostly Avatar asked Mar 14 '11 14:03

Ghostly


People also ask

How do you format a string in Python?

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.

What is difference between list and tuple and 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.

Which are the different ways to perform string formatting?

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.


1 Answers

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)
like image 56
Jochen Ritzel Avatar answered Sep 22 '22 04:09

Jochen Ritzel