温馨提示×

如何通过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