温馨提示×

python format函数的用法是什么

小亿
74
2023-10-31 21:15:44
栏目: 编程语言

Python的format函数用于格式化字符串,将一个或多个值插入到字符串中。它可以在字符串中指定占位符,然后使用format函数将对应的值替换到占位符的位置上。

format函数的基本语法如下:

formatted_string = "字符串模板".format(value1, value2, ...)

在字符串模板中,可以使用花括号{}作为占位符,然后在format函数中按顺序传入对应的值来替换这些占位符。

以下是一些常用的用法示例:

  1. 顺序替换
name = "Alice"
age = 25
text = "My name is {} and I am {} years old.".format(name, age)
print(text)  # 输出: My name is Alice and I am 25 years old.
  1. 根据索引替换
name = "Alice"
age = 25
text = "My name is {0} and I am {1} years old.".format(name, age)
print(text)  # 输出: My name is Alice and I am 25 years old.
  1. 根据关键字替换
name = "Alice"
age = 25
text = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(text)  # 输出: My name is Alice and I am 25 years old.
  1. 格式化数字
pi = 3.14159265359
formatted_pi = "{:.2f}".format(pi)
print(formatted_pi)  # 输出: 3.14
  1. 对齐和填充
text = "{:<10}{}".format("left", "right")
print(text)  # 输出: "left      right"

以上只是format函数的一些常用用法,还有更多的格式化选项可以参考官方文档。

0