admin 管理员组

文章数量: 887021


2023年12月19日发(作者:网页斗地主游戏源码)

python中print的format用法

在Python中,`print`函数的`format`用法是通过在字符串中使用花括号`{}`来表示要格式化的值,再使用`format()`方法传入要填充到字符串中的值。

以下是几种常见的`format`用法示例:

1. 顺序插入值:

python

name = "Alice"

age = 25

print("My name is {}, and I am {} years old.".format(name, age))

输出:`My name is Alice, and I am 25 years old.`

2. 根据索引插入值:

python

name = "Bob"

age = 30

print("My name is {1}, and I am {0} years old.".format(age, name))

输出:`My name is Bob, and I am 30 years old.`

3. 使用关键字参数插入值:

python

name = "Charlie"

age = 35

print("My name is {name}, and I am {age} years

old.".format(name=name, age=age))

输出:`My name is Charlie, and I am 35 years old.`

4. 使用不同的格式化选项:

python

number = 3.14159

print("Pi is approximately {:.2f}.".format(number))

输出:`Pi is approximately 3.14.`

python

total = 100

percentage = 80

print("You got {percent:.1%} of {total}

points.".format(percent=percentage/total, total=total))

输出:`You got 80.0% of 100 points.`

5. 使用变量值自动格式化:

python

name = "David"

age = 40

print(f"My name is {name}, and I am {age+10} years old.")

输出:`My name is David, and I am 50 years old.`

希望以上解答能对你有所帮助!


本文标签: 使用 字符串 插入 解答 有所