python格式化输出

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() 方法将模板字符串中的占位符替换为指定的值。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值