python字符串方法format()如何使用

python字符串方法format()如何使用

1、格式字符串中用花括号表示待插入值的位置、索引名称和格式,并在format方法参数中写出待插入值。

2、转换标志:跟随感叹号后的单词表示以相应的格式转换给定的值。

格式说明符:跟随冒号后的表现,用于详细指定字符串的格式。

实例

JavaScript

>>> # 指定表示方式
>>> print('in decimal: {0:d}\nin binary : {0:b}'.format(10))
# in decimal: 10
# in binary : 1010
>>> print('in fixed-point notation: {0:f}\nin scientific  notation: {0:e}'.format(0.25))
# in fixed-point notation: 0.250000
# in scientific  notation: 2.500000e-01
 
>>> # 指定精度
>>> print("{0:.2f}".format(1/3))
# 0.33
 
>>> # 指定宽度,默认右对齐
>>> print("{0:10.2f}".format(1/4))
#       0.25
 
>>> # 指定对齐方式,默认用空格填充
>>> print("{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}".format(1/6))
# 0.17      
#    0.17   
#       0.17
 
>>> # 指定对齐方式,并指定填充字符
>>> print("{0:*<10.2f}\n{0:*^10.2f}\n{0:*>10.2f}".format(1/7))
# 0.14******
# ***0.14***
# ******0.14

以上就是python字符串方法format()的使用,希望对大家有所帮助。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值