Python format基本用法

在 Python 中,format() 是一种用于格式化字符串的内置方法。它允许您通过将占位符替换为实际的值来创建格式化的字符串。下面是一些使用 format() 方法的常见用法:

基本用法:

 1.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.

在上述示例中,我们使用占位符 {} 来表示需要插入值的位置,然后通过 format() 方法中的参数按顺序提供相应的值。

2.通过位置索引指定参数:

name = "Bob"

age = 30

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

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

在这个示例中,我们使用 {0}{1} 来指定参数的位置索引。这样可以控制参数值的顺序,而不仅仅依赖于它们在 format() 方法中的顺序。

3.通过关键字参数指定参数:

name = "Charlie"

age = 35

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

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

在这个示例中,我们使用关键字参数来指定参数的值。在占位符中,我们使用对应参数的关键字名称(na)。

4.格式化数字:

number = 3.14159

print("The value of pi is approximately {:.2f}.".format(number))

输出:The value of pi is approximately 3.14.

在这个示例中,我们使用占位符 {: .2f} 来指定浮点数的格式,其中 .2f 表示保留两位小数。

这只是一些 format() 方法的常见用法示例。format() 方法还支持更多的格式选项和修饰符,例如对齐、填充等。您可以在 Python 官方文档中详细了解 str.format() 的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值