欢迎访问宙启技术站
智能推送

如何使用Python的format()函数输出格式化字符串?

发布时间:2023-06-08 20:04:17

Python的format()函数是字符串的内置方法,用于格式化字符串。它可以将字符串中的占位符替换为指定的值,并将其格式化成一个更易读的字符串。

format()函数的基本语法如下所示:

string.format(arguments)

其中,string是待格式化的字符串,arguments是一个或多个要传入字符串的值,用来代替占位符。

下面是一个最简单的示例:

message = "Hello, my name is {} and I am {} years old."
print(message.format("John", 27))

在这个示例中,我们使用{}作为占位符并调用format()函数传递两个参数,即"John"和27。调用format()函数会将占位符替换为这些参数的值,并返回格式化后的字符串:

Hello, my name is John and I am 27 years old.

除了{}外,还可以使用{0}、{1}这样的格式来指定参数的位置。例如:

message = "My name is {0}, and I am from {1}."
print(message.format("Alice", "New York"))

这将输出:

My name is Alice, and I am from New York.

可以使用冒号(:)来添加格式化选项到占位符中。例如:

price = 10.5
message = "The price is ${:.2f}.".format(price)
print(message)

在这个示例中,我们使用冒号来添加了一个精度为两位小数的浮点数格式化选项。这将输出:

The price is $10.50.

以下是一些常见的格式化选项:

| 格式化选项 | 释义 |

| ---------- | ----------------------------------- |

| d | 整数,十进制 |

| o | 整数,八进制 |

| x | 整数,小写十六进制 |

| X | 整数,大写十六进制 |

| f | 浮点数,小数点后保留6位 |

| e | 浮点数,科学计数法(小写'e'格式) |

| E | 浮点数,科学计数法(大写'E'格式) |

| % | 百分数形式 |

| s | 字符串 |

例如,以下代码可以演示格式化选项的用法:

print("The integer is {:d}".format(10))    # 输出:The integer is 10
print("The octal number is {:o}".format(10))    # 输出:The octal number is 12
print("The hexadecimal number is {:x}".format(255))    # 输出:The hexadecimal number is ff
print("The float is {:.2f}".format(3.1415926))    # 输出:The float is 3.14
print("The number is {:e}".format(100000000))    # 输出:The number is 1.000000e+08
print("The percent is {:.2%}".format(0.1234))    # 输出:The percent is 12.34%
print("The string is {}".format("hello"))    # 输出:The string is hello

格式化字符串还可以使用字典作为参数来传递多个值。在这种情况下,可以使用占位符{key}来引用字典的键。例如:

person = {"name": "Bob", "age": 35}
message = "My name is {name}, and I am {age} years old.".format(**person)
print(message)

这将输出:

My name is Bob, and I am 35 years old.

最后,Python的format()函数还支持位置参数和关键字参数的混合使用,以及更加复杂的格式化选项。format()函数是Python中最常用的字符串格式化方法之一,使用它可以轻松地将复杂的数据结构转换为易读的字符串。