Ghostly
Ghostly

Reputation: 203

How to use list (or tuple) as String Formatting 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 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

Upvotes: 20

Views: 64093

Answers (8)

dyingoptimist
dyingoptimist

Reputation: 113

Building upon yan's answer for the newer .format() method, if one has a dictionary with more than one value for a key, use index with key for accessing different values.

>>> s = {'first':['python','really'], 'second':'rocks'}
>>> x = '{first[0]} --{first[1]}-- {second}'.format(**s)
>>> x
'python --really-- rocks'

Caution: It's a little different when you have to access one of the values against a key independent of .format(), which goes like this:

>>> value=s['first'][i]

Upvotes: 3

Ali Sajjad Rizavi
Ali Sajjad Rizavi

Reputation: 4520

We can convert a list to arguments to .format(...) using * with the name of list. Like this: *mylist

See the following code:

mylist = ['Harry', 'Potter']
s = 'My last name is {1} and first name is {0}'.format(*mylist)
print(s)

Output: My last name is Potter and first name is Harry.

Upvotes: 0

Michael come lately
Michael come lately

Reputation: 9422

If you are serious about injecting as many as 26 strings into your format, you might want to consider naming the placeholders. Otherwise, someone looking at your code is going to have no idea what s[17] is.

fields = {
    'username': 'Ghostly',
    'website': 'Stack Overflow',
    'reputation': 6129,
}

fmt = '''
Welcome back to {website}, {username}!
Your current reputation sits at {reputation}.
'''

output = fmt.format(**fields)

To be sure, you can continue to use a list and expand it like the end of Jochen Ritzel's answer, but that's harder to maintain for larger structures. I can only imagine what it would look like with 26 of the {} placeholders.

fields = [
    'Ghostly',
    'Stack Overflow',
    6129,
]

fmt = '''
Welcome back to {}, {}!
Your current reputation sits at {}.
'''

output = fmt.format(*fields)

Upvotes: 1

123
123

Reputation: 315

Talk is cheap, show you the code:

>>> tup = (10, 20, 30)
>>> lis = [100, 200, 300]
>>> num = 50
>>> print '%d      %s'%(i,tup)
50      (10, 20, 30)
>>> print '%d      %s'%(i,lis)
50      [100, 200, 300]
>>> print '%s'%(tup,)
(10, 20, 30)
>>> print '%s'%(lis,)
[100, 200, 300]
>>> 

Upvotes: 0

Suman-PHP4U
Suman-PHP4U

Reputation: 1185

Check the following example

List Example

data = ["John", "Doe", 53.44]
format_string = "Hello"

print "Hello %s %s your current balance is %d$" % (data[0],data[1],data[2])

Hello John Doe your current balance is 53$

Tuple example

data = ("John", "Doe", 53.44)
format_string = "Hello"

print "Hello %s %s your current balance is %d$" % (data[0],data[1],data[2])

Hello John Doe your current balance is 53$

Upvotes: -1

Jochen Ritzel
Jochen Ritzel

Reputation: 107786

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)

Upvotes: 66

yan
yan

Reputation: 20992

If you want to use a list of items, you can just pass a tuple directly:

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

Or you can use a dictionary to make your list earlier:

s = {'first':'python', 'second':'rocks'}
x = '%(first)s %(second)s' % s

Upvotes: 1

Lixas
Lixas

Reputation: 7318

There is how to join tuple members:

x = " ".join(YourTuple)

Space is your tuple members separator

Upvotes: 3

Related Questions