Python 3.6 中带元组的格式化字符串文字 [英] Formatted string literals in Python 3.6 with tuples

查看:52
本文介绍了Python 3.6 中带元组的格式化字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 str.format() 我可以使用元组来访问参数:

<预><代码>>>>'{0}, {1}, {2}'.format('a', 'b', 'c')'a, b, c'

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

但是对于以f"(f 字符串)为前缀的新格式化字符串文字,我该如何使用元组?

f'{0}, {1}, {2}'.(*t) # 不起作用

解决方案

你的第一个 str.format() 调用是一个带有 3 个参数的常规方法调用,那里没有涉及元组.您的第二个调用使用 * splat 调用语法;str.format() 调用接收 3 个单独的参数,它不在乎那些来自元组.

使用 f 格式化字符串不使用方法调用,因此您不能使用任何一种技术.f'..' 格式化字符串中的每个插槽都作为正则 Python 表达式执行.

您必须直接从元组中提取您的值:

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

或者首先将元组扩展为新的局部变量:

a, b, c = tf'{a}, {b}, {c}'

或者干脆继续使用str.format().您不必使用 f'..' 格式化字符串,这是该语言的新附加功能,而不是替换 str.format().

来自 PEP 498 -- 文字字符串插值:

<块引用>

本 PEP 不建议删除或弃用任何现有的字符串格式机制.

With str.format() I can use tuples for accesing arguments:

>>> '{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'{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. Your second call uses the * splat call syntax; the str.format() call receives 3 separate individual arguments, it doesn't care that those came from a tuple.

Formatting strings with f don't use a method call, so you can't use either technique. Each slot in a f'..' formatting string is instead executed as a regular Python expression.

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(). 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().

From PEP 498 -- Literal String Interpolation:

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.

这篇关于Python 3.6 中带元组的格式化字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆