-2

如何使用 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'
4

1 回答 1

0

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

Template('Hello ${name}. It is $$$cost').substitute(d)
# 'Hello Johnny. It is $10'
于 2018-08-15T07:16:23.717 回答