Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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_String_Format - Fatal编程技术网

Python-将格式化的数字添加到字符串

Python-将格式化的数字添加到字符串,python,string,format,Python,String,Format,使用Python v2,我有以下代码: print ("Total of the sale is: ${:,.2f}".format(TotalAmount)) 这是获取名为TotalAmount的字符串并对其进行格式化,使其看起来像:$100.00,即:货币值,无论数字是什么 有没有办法将格式化输出写入字符串 谢谢您的帮助。只需将其保存到变量中,而不是将其传递到打印 >>> dog = "doggy" >>> pets = "cat and %s" % d

使用Python v2,我有以下代码:

print ("Total of the sale is: ${:,.2f}".format(TotalAmount))
这是获取名为TotalAmount的字符串并对其进行格式化,使其看起来像:$100.00,即:货币值,无论数字是什么

有没有办法将格式化输出写入字符串


谢谢您的帮助。

只需将其保存到变量中,而不是将其传递到打印

>>> dog = "doggy"
>>> pets = "cat and %s" % dog
>>> print pets
cat and doggy

只需将其保存到变量,而不是将其传递到打印

>>> dog = "doggy"
>>> pets = "cat and %s" % dog
>>> print pets
cat and doggy

尝试将此格式设置为小数点后2位:

for amt in (123.45, 5, 100):
    val = "Total of the sale is: $%0.2f" % amt
    print val

Total of the sale is: $123.45
Total of the sale is: $5.00
Total of the sale is: $100.00

尝试将此格式设置为小数点后2位:

for amt in (123.45, 5, 100):
    val = "Total of the sale is: $%0.2f" % amt
    print val

Total of the sale is: $123.45
Total of the sale is: $5.00
Total of the sale is: $100.00

使用f类型格式时,TotalAmount应该是整数、浮点或十进制数字,而不是字符串。您的print语句很好,尽管pythonver2.x中不需要paren,但在本例中它们是可以的,因为它们被认为是print语句的单个表达式的一部分。对于将来可能升级到3.x版也是一个好主意。

当您使用f类型格式时,TotalAmount应该是int、float或Decimal数字,而不是字符串。您的print语句很好,尽管pythonver2.x中不需要paren,但在本例中它们是可以的,因为它们被认为是print语句的单个表达式的一部分。对于将来可能升级到3.x版也是一个好主意