python3中format函数的用法是什么

2024-03-06

在Python3中,format()函数是用于格式化字符串的方法。它可以将变量、常量或表达式的值插入到字符串中的特定位置。

format()函数的用法有两种形式:

  1. 位置参数形式:

    "字符串{}".format(值)
    

    这种形式使用占位符{}来标识要插入的值的位置,然后通过format()函数的参数按位置将值插入到对应位置。

  2. 关键字参数形式:

    "字符串{关键字}".format(关键字=值)
    

    这种形式使用占位符{关键字}来标识要插入的值的位置,然后通过format()函数的关键字参数将值插入到对应位置。

以下是一些示例:

name = "Alice"
age = 25

# 位置参数形式
print("My name is {}, and I am {} years old.".format(name, age))

# 关键字参数形式
print("My name is {name}, and I am {age} years old.".format(name=name, age=age))

输出:

My name is Alice, and I am 25 years old.
My name is Alice, and I am 25 years old.

除了使用位置参数和关键字参数外,format()函数还支持其他的格式化选项,如指定数值的精度、填充字符、对齐方式等。详细的格式化选项可以参考Python官方文档中的字符串格式化部分。