首页 > 编程语言 > 详细

python- 字符串格式化 format函数

时间:2021-01-21 12:30:28      阅读:24      评论:0      收藏:0      [点我收藏+]
# 字符串格式化 format函数
# 通过位置参数,按照位置顺序替换前面的{}占位符
s1 = "name:{}, socre:{}".format("tom",89)
# 关键字参数或命名参数
s2 = "name:{0},socre:{score} ".format("tom",score=99)
# 如果是列表之类的用下标
s3 = "name:{0[0]},socre:{0[1]} ".format(("tom",78))
#对齐,冒号前面的数字表示对应的位置,后面的箭头表示斯左对齐还是右对齐
#箭头指哪边就往哪边对齐。>后面的数字表示占多少个字符,默认补空格,冒号后面可以
# 接其他字符,如*,表示不够位数,用*补齐
s4 = "{0:>2}+{1:>2}={2:<3}".format(1,1,1+1)
s4 = "{0:*>2}+{1:->2}={2:a<3}".format(a,b,c)
# 居中
s5 = {:^30}.format(centered)
s6 = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
#带进制前缀
s7 = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)

print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(s6)
print(s7)
name:tom, socre:89
name:tom,socre:99 
name:tom,socre:78 
*a+-b=caa
           centered           
int: 42; hex: 2a; oct: 52; bin: 101010
int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010

python- 字符串格式化 format函数

原文:https://www.cnblogs.com/mqhuang/p/14306243.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!