Python中字符串格式化之format用法

这篇博客介绍了Python中的字符串格式化方法,重点讲解了format函数的使用,包括通过位置、列表、字典等方式嵌入值,并展示了如何进行格式转换。强调了format方法的灵活性和未来兼容性,建议避免使用即将废弃的%操作符。
摘要由CSDN通过智能技术生成

在Python学习过程中,遇到字符串格式化输出,故记录一下。

以前字符串格式化方法常采用%,这种方法在将来的版本中可能被遗弃。

以后尽量采用字符串的format方法,该方法较%更加的灵活和强大。format()方法格式化特定的值,并将它们嵌入待格式化字符串中的占位符处。该占位符为curly brackets:{}

用法

string.format(value1, value2,…)

value1, value2, … 输入参数值,required
这些值可以是以逗号分隔的列表(list)键值列表key=value、或者是它们的组合等,这些值可以是任意数据类型。

占位符可以通过名字索引{iddex_name},数字索引{0},或者空的占位符{ }等。

例子

  • 通过位置直接嵌入
test1="My name is {}. I'm {}.".format('SeisTang',18)
test2="My name is {0}. I'm {1}.".format('SeisTang',18)
test3="My name is {0}. I'm {1}. You can call me {0}.".format('SeisTang',18)
print(test1)
print(test2)
print(test3)

output:

My name is SeisTang. I’m 18.
My name is SeisTang. I’m 18.
My name is SeisTang. I’m 18. You can call me SeisTang.

可以看到,format会把参数values按照位置顺序嵌入到字符串string中,同一个参数可以嵌入多次

  • 通过列表list来嵌入
list1=['SeisTang',18]
list2=['Hello','Tang']
test1="My name is {0[0]}. I'm {0[1]}. {1[0]} {1[1]}.".format(list1,list2)
test2="My name is {tl1[0]}. I'm {tl1[1]}. {tl2[0]} {tl2[1]}.".format(tl1=list1,tl2=list2)
print(test1)
print(test2)

output

My name is SeisTang. I’m 18. Hello Tang.
My name is SeisTang. I’m 18. Hello Tang.

  • 通过key-value来嵌入
test1="My name is {name}. I'm {age}.".format(name='SeisTang',age=18)
print(test1)

output

My name is SeisTang. I’m 18.

  • 当然也可以通过字典的键进行嵌入
dict={'name':'SeisTang','age':18}
test1="My name is {0[name]}. I'm {0[age]}.".format(dict)
print(test1)

输出与上面相同。

  • 也可以使用**符号将上面dict作为传递的关键参数。

格式转换

针对数字,如3.1415926,希望只输出小数点后两位,可在占位符中加入{:.2f}这些规则与C语言中类似,此处不再赘述,可查阅其他相关文献资料。

test1="How {} are you? I'm {:.2f}m.".format('tall',1.8321)
print(test1)

output

How tall are you? I’m 1.83m.

如有错误,请指正,非常感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值