关于python的格式化输出
price = input("please input a number: ")
txt = "The price is {:.2f} dollars"
print(txt.format(price))
会报错:
ValueError: Unknown format code 'f' for object of type 'str'
但是改成这样:
price = int(input("please input a number: "))
txt = "The price is {:.2f} dollars"
print(txt.format(price))
即可运行,这里的int改成float什么的一样可以
这是为什么捏?
因为不加默认是字符串类型,整型或者浮点型才能进行格式控制输出
{:.2f}是对数值以浮点数保留2位小数的格式输出,这就要求的format中提供的参数必须是数值(int或float)类型,不能是字符串(str)类型。
{:.2f}
格式化输出控制时,实际是把format中的变量传到f中,
因为是对数值型数据进行格式化输出的操作,所以传入的必须要是数值型数据。