【问题标题】:Avoid duplicating arguments to str.format?避免将参数复制到 str.format?
【发布时间】:2019-06-03 08:28:19
【问题描述】:

我目前在我的代码中使用字符串格式,但是我发现我很难编码来显示重复的变量。有没有更有效的方法来做到这一点

print("Hello this is {} and {} and {} - Hello this is {} and {} and {} ".format(versionP, versionS, versionT, versionP, versionS, versionT))

结果是我想要的结果,但我需要在多个情况下重复这一点,这可能会变得乏味。有没有办法只写一次变量?

【问题讨论】:

  • 这取决于您的 Python 版本。 Aaron_ab 提出的 F 弦从 3.6 开始提供。

标签: python python-3.x string format


【解决方案1】:

您可以指定位置,str.format 会知道使用哪些参数:

a, b, c = 1, 2, 3
string = "This is {0}, {1}, and {2}. Or, in reverse: {2}, {1}, {0}"
string.format(a, b, c)
# 'This is 1, 2, and 3. Or, in reverse: 3, 2, 1'

你也可以传递关键字参数,或者解压字典:

a, b, c = 1, 2, 3
string = """This is {versionP}, {versionS}, and {versionT}. 
            Or, in reverse: {versionT}, {versionS}, {versionP}"""
# string.format(versionP=a, versionS=b, versionT=c)
string.format(**{'versionP': a, 'versionS': b, 'versionT': c})
# This is 1, 2, and 3. 
#       Or, in reverse: 3, 2, 1

【讨论】:

  • 请注意,当字典中没有要放置的相关键时,使用字典的技术会引发异常..
  • OP 注释:我已将我的答案转换为可运行的示例,以便您自己了解它是如何工作的。该过程与您的用例相同。
【解决方案2】:

Python 3.6

我觉得它干净简单:

print(f"Hello this is {versionP} and {versionS} and {versionT} - 
        Hello this is {versionP} and {versionS} and {versionT}")

您甚至可以在 f-formatting 或 nested f-strings 中使用 evaluate 方法

【讨论】:

  • 好答案,但这假设 OP 有 python3.6
  • 好点。这仅适用于 3.6 及更高版本。我也喜欢您对字典的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2013-03-20
  • 2014-10-13
  • 2019-03-17
  • 2022-05-22
  • 2015-05-03
  • 2015-06-24
相关资源
最近更新 更多