在Python中,你可以使用字符串的format()方法来对表达式进行格式化。format()方法允许你在字符串中插入变量值、表达式的结果或其他格式化选项。
format()
下面是几种常用的格式化方法:
插入变量值:
name = "Alice" age = 25 print("My name is {} and I'm {} years old.".format(name, age))
输出:My name is Alice and I'm 25 years old.
My name is Alice and I'm 25 years old.
指定变量的位置:
name = "Alice" age = 25 print("My name is {0} and I'm {1} years old. {0}!".format(name, age))
输出:My name is Alice and I'm 25 years old. Alice!
My name is Alice and I'm 25 years old. Alice!
使用关键字参数:
name = "Alice" age = 25 print("My name is {name} and I'm {age} years old.".format(name=name, age=age))
对数字进行格式化:
number = 3.14159 print("The value of pi is approximately {:.2f}".format(number))
输出:The value of pi is approximately 3.14
The value of pi is approximately 3.14
以上只是一些常见的格式化方法,format()方法还支持更多的格式选项,例如对齐、填充、指定宽度等。你可以参考Python的官方文档以获取更详细的信息:https://docs.python.org/3/library/string.html#format-string-syntax
原文链接:codingdict.net