您的位置:首页 > 编程语言 > Python开发

Python字符串格式化输出

2017-10-10 22:53 525 查看
在Python可以使用字符串的format函数替换掉字符串中的
{}
格式化描述符号从而达到C中的printf效果

示例代码:

#!/usr/bin/python3

amount = float(input("Enter amount: "))
inrate = float(input("Enter Interest rate: "))
period = float(input("Enter period: "))

value = 0
year = 1
while year <= period:
value = amount + (inrate * amount)
print("Year {} Rs. {:.2f}".format(year, value))
amount = value
year += 1

print("Total = {:.3f}".format(value))


输出

Enter amount: 10000

Enter Interest rate: 0.2

Enter period: 10

Year 1 Rs. 12000.00

Year 2 Rs. 14400.00

Year 3 Rs. 17280.00

Year 4 Rs. 20736.00

Year 5 Rs. 24883.20

Year 6 Rs. 29859.84

Year 7 Rs. 35831.81

Year 8 Rs. 42998.17

Year 9 Rs. 51597.80

Year 10 Rs. 61917.36

Total = 61917.364

#!/usr/bin/python3

fahrenheit = 0
print("Fahrenheit Cesius")
while fahrenheit <= 250:
celsius = (fahrenheit - 32) / 1.8
print("{:5d} {:10.2f}".format(fahrenheit, celsius))
fahrenheit = fahrenheit + 25


输出

Fahrenheit Cesius

0 -17.78

25 -3.89

50 10.00

75 23.89

100 37.78

125 51.67

150 65.56

175 79.44

200 93.33

225 107.22

250 121.11
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: