温馨提示×

如何通过format函数自定义输出格式

小樊
102
2024-09-21 05:39:45
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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.

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:String.format的输出格式能自定义吗

0