溫馨提示×

如何通過format函數自定義輸出格式

小樊
81
2024-09-21 05:39:45
欄目: 編程語言

在Python中,format()函數允許你自定義輸出格式。它有多種用法,包括使用位置參數、關鍵字參數和格式說明符。以下是一些示例:

  1. 使用位置參數:
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))

輸出:

My name is Alice and I am 30 years old.
  1. 使用關鍵字參數:
name = "Alice"
age = 30
print("My name is {person} and I am {years} years old.".format(person=name, years=age))

輸出:

My name is Alice and I am 30 years old.
  1. 使用格式說明符:
  • %s:字符串
  • %d:整數
  • %f:浮點數
  • %.2f:保留兩位小數的浮點數
  • %x:十六進制數
num1 = 123
num2 = 3.14159
print("The hexadecimal representation of {} is {:x}.".format(num1, num2))

輸出:

The hexadecimal representation of 123 is 7b.

你還可以使用格式說明符的寬度和精度:

num1 = 12345
num2 = 3.14159
print("The number {} has {} digits and its float representation is {:.2f}.".format(num1, len(str(num1)), num2))

輸出:

The number 12345 has 5 digits and its float representation is 3.14.

0