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格式化输出format
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.`
希望以上解答能对你有所帮助!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。