在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