Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python模板字符串设置货币格式_Python_Template Strings - Fatal编程技术网

使用python模板字符串设置货币格式

使用python模板字符串设置货币格式,python,template-strings,Python,Template Strings,如何使用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

如何使用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'
$$转义美元符号,因此需要三个美元符号:

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

很明显,$$给了您一个美元符号,${cost}插入了您的变量。你试过$${cost}吗?可能是@khelwood的复制品,谢谢