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

   2024-09-30 7490
核心提示:在Python中,format()函数允许你自定义输出格式。它有多种用法,包括使用位置参数、关键字参数和格式说明符。以下是一些示例:使

在Python中,format()函数允许你自定义输出格式。它有多种用法,包括使用位置参数、关键字参数和格式说明符。以下是一些示例:

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

输出:

My name is Alice and I am 30 years old.
使用关键字参数:
name = "Alice"age = 30print("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.
使用格式说明符:%s:字符串%d:整数%f:浮点数%.2f:保留两位小数的浮点数%x:十六进制数
num1 = 123num2 = 3.14159print("The hexadecimal representation of {} is {:x}.".format(num1, num2))

输出:

The hexadecimal representation of 123 is 7b.

你还可以使用格式说明符的宽度和精度:

num1 = 12345num2 = 3.14159print("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.

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号