简体   繁体   English

如何使用列表(或元组)作为字符串格式值

[英]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现在我想替换更长的列表,并分别添加所有列表值,例如 s[0]、s[1]、... s[n],似乎不正确

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). [4] 否则,values 必须是一个元组,其中的项目数与格式字符串指定的数量完全相同,或者是单个映射对象(例如,字典)。

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我想更紧凑地更改% (s[0], s[1], ... , s[26])而不手动输入每个值

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.当然,s 中的项数必须与格式字符串中的插入点数相同。

Since 2.6 you can also use the new format method, for example:从 2.6 开始,您还可以使用新的format方法,例如:

x = '{} {}'.format(*s)

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.建立在@yan 对较新 .format 方法的回答上,如果一个字典的键值超过一个,请使用带键的索引来访问不同的值。

>>> 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:注意:当您必须根据独立于 .format() 的键访问其中一个值时,它几乎没有什么不同,如下所示:

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

There is how to join tuple members:有如何加入元组成员:

x = " ".join(YourTuple)

Space is your tuple members separator空格是你的元组成员分隔符

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.如果您真的想在格式中注入多达 26 个字符串,您可能需要考虑命名占位符。 Otherwise, someone looking at your code is going to have no idea what s[17] is.否则,查看您代码的人将不知道s[17]是什么。

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.可以肯定的是,您可以继续使用列表并像Jochen Ritzel 的答案一样扩展它但是对于更大的结构来说这更难维护。 I can only imagine what it would look like with 26 of the {} placeholders.我只能想象使用 26 个{}占位符会是什么样子。

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.我们可以使用带有列表名称的*list转换为.format(...)参数。 Like this: *mylist像这样: *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$你好 John Doe 你目前的余额是 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$你好 John Doe 你目前的余额是 53 美元

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM