【问题标题】:Format currency using python template strings使用 python 模板字符串格式化货币
【发布时间】:2019-01-22 01:38:08
【问题描述】:

如何使用 python 模板字符串格式化货币?我的目标是生成以下字符串:

'Hello Johnny. It is $10'

我尝试了以下方法:

from string import Template
d = {'name': 'Johnny', 'cost': 10}

Template('Hello ${name}. It is ${cost}').substitute(d)
# 'Hello Johnny. It is 10'

Template('Hello ${name}. It is $${cost}').substitute(d)
# 'Hello Johnny. It is ${cost}'

Template('Hello ${name}. It is $$cost').substitute(d)
# 'Hello Johnny. It is $cost'

【问题讨论】:

  • 似乎很清楚$$ 给你一个美元符号,${cost} 插入你的变量。那你试过$$${cost} 吗?
  • @khelwood 做到了,谢谢

标签: python template-strings


【解决方案1】:

$$ 转义了美元符号,因此需要三个美元符号:

Template('Hello ${name}. It is $$$cost').substitute(d)
# 'Hello Johnny. It is $10'

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多