python的format函数如何使用占位符

Python的format()函数可以使用花括号{}作为占位符,具体用法如下:

  1. 使用位置参数占位符 可以使用位置参数占位符{}来指定要格式化的参数的位置,例如:
 

pythonCopy code

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

输出结果为:

 

plaintextCopy code

My name is Alice, and I am 18 years old.

  1. 使用关键字参数占位符 还可以使用关键字参数占位符{name}来指定要格式化的参数的名称,例如:
 

pythonCopy code

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

输出结果为:

 

plaintextCopy code

My name is Bob, and I am 20 years old.

  1. 使用位置参数和关键字参数混合占位符 还可以混合使用位置参数和关键字参数来格式化字符串,例如:
 

pythonCopy code

print("My name is {0}, and I am {1} years old. I come from {country}.".format("Charlie", 22, country="China"))

输出结果为:

 

plaintextCopy code

My name is Charlie, and I am 22 years old. I come from China.

  1. 指定格式化类型 在占位符{}中可以使用冒号:来指定要格式化的类型,例如:
 

pythonCopy code

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

输出结果为:

 

plaintextCopy code

The value of pi is approximately 3.14.

这里使用了浮点数类型的格式化,:.2f表示保留2位小数。具体格式化类型可以参考Python官方文档。

format使用字符'0'来填充空格

如果想要在format中使用字符'0'来填充空格,可以在占位符{}中使用冒号:来指定填充的字符和宽度。具体用法如下:

 

pythonCopy code

number = 42 print("The answer is {:0>4}".format(number))

输出结果为:

 

plaintextCopy code

The answer is 0042

这里的{:0>4}表示使用字符'0'来填充空格,宽度为4。其中'>'表示右对齐,'0'表示使用字符'0'来填充空格。如果要左对齐,可以使用'<';如果要居中对齐,可以使用'^'。如下所示:

 

pythonCopy code

number = 42 print("The answer is {:<4}".format(number)) # 左对齐 print("The answer is {:^4}".format(number)) # 居中对齐

输出结果分别为:

 

plaintextCopy code

The answer is 42 The answer is 42

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值