开发者

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
          ..开发者_如何学Go. 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


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)


There is how to join tuple members:

x = " ".join(YourTuple)

Space is your tuple members separator


building up on @yan 's answer for newer .format method, if one has a dictionary with more than one values 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: Its 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]


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


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]
>>> 


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)


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.


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$

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜