python格式化输出
.format()
在 Python 中,格式化输出可以使用字符串的 format() 方法。这个方法可以将字符串中的占位符替换为指定的变量值。
以下是一个例子:
a=3
b=4
print('{}+{}={}'.format(a,b,a+b)) # 3+4=7
name = "Alice"
age = 25
height = 1.65
print("My name is {}, I'm {} years old and {} meters tall.".format(name, age, height))
在这个例子中,{}
是占位符,用来指示变量将被插入到字符串中。format()
方法接受一个或多个参数,这些参数将按照顺序替换占位符。
输出将是:
My name is Alice, I'm 25 years old and 1.65 meters tall.
你还可以使用更详细的格式指令来控制输出格式,例如:
pi = 3.1415926
print("The value of pi is {:.2f}".format(pi))
在这个例子中,{:.2f}
指令表示将输出一个浮点数,保留小数点后两位。输出将是:
The value of pi is 3.14
x = 3.1415926
s = "{:>9.3f}".format(x)
print(s)
3.142
{}
是占位符,用于指示变量将被插入到字符串中。
:
表示格式指令的开始。
>
表示右对齐。
9
表示字符串的长度为 9。
.3f
表示保留小数点后 3 位,并格式化为浮点数。
f-strings
f-strings 是 Python 3.6 中引入的新特性,它允许将变量值插入到字符串中的占位符中。f-strings 以f
字符为前缀,然后在字符串中使用花括号 {} 来引用变量。例如:
name = "Alice"
age = 25
print(f"My name is {name}, and I'm {age} years old.")
# My name is Alice, and I'm 25 years old.
%-formatting
%-formatting 是另一种用于格式化输出的方法,它使用百分号 % 作为格式化符号,然后根据数据类型使用不同的格式指令来格式化输出。例如:
name = "Alice"
age = 25
print("My name is %s, and I'm %d years old." % (name, age))
# My name is Alice, and I'm 25 years old.
在这个例子中,%s
用来格式化字符串,%d
用来格式化整数。%
符号后面的括号中是一个元组,包含要替换的变量值。
Template strings
模板字符串是另一种用于格式化输出的方式,它使用美元符号 $ 作为占位符。模板字符串使用 Template 类来创建。例如:
from string import Template
name = "Alice"
age = 25
t = Template("My name is $name, and I'm $age years old.")
print(t.substitute(name=name, age=age))
# My name is Alice, and I'm 25 years old.
在这个例子中,占位符以 $ 开头,然后使用关键字参数来传递变量值。使用 substitute() 方法将模板字符串中的占位符替换为指定的值。