简体   繁体   English

Python 3.6 中带元组的格式化字符串文字

[英]Formatted string literals in Python 3.6 with tuples

With str.format() I can use tuples for accesing arguments:使用str.format()我可以使用元组来访问参数:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')

'a, b, c'

or

>>> t = ('a', 'b', 'c')
>>> '{0}, {1}, {2}'.format(*t)

'a, b, c'

But with the new formatted string literals prefixed with 'f' (f-strings), how can I use tuples?但是对于以“f”(f 字符串)为前缀的新格式化字符串文字,我该如何使用元组?

f'{0}, {1}, {2}'.(*t)  # doesn't work

Your first str.format() call is a regular method call with 3 arguments, there is no tuple involved there .您的第一个str.format()调用是带有 3 个参数的常规方法调用,那里不涉及元组 Your second call uses the * splat call syntax;您的第二个调用使用* splat 调用语法; the str.format() call receives 3 separate individual arguments, it doesn't care that those came from a tuple. str.format()调用接收 3 个单独的参数,它不在乎那些来自元组。

Formatting strings with f don't use a method call, so you can't use either technique.使用f格式化字符串不使用方法调用,因此您不能使用任何一种技术。 Each slot in a f'..' formatting string is instead executed as a regular Python expression. f'..'格式字符串中的每个插槽都作为正则 Python 表达式执行。

You'll have to extract your values from the tuple directly:您必须直接从元组中提取您的值:

f'{t[0]}, {t[1]}, {t[2]}'

or first expand your tuple into new local variables:或者首先将元组扩展为新的局部变量:

a, b, c = t
f'{a}, {b}, {c}'

or simply continue to use str.format() .或者干脆继续使用str.format() You don't have to use an f'..' formatting string, this is a new, additional feature to the language, not a replacement for str.format() .不必使用f'..'格式化字符串,这是一个新的,额外的功能的语言,而不是替代str.format()

From PEP 498 -- Literal String Interpolation :来自PEP 498 -文字字符串插值

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.本 PEP 不建议删除或弃用任何现有的字符串格式化机制。

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

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