知行编程网知行编程网  2022-08-21 04:30 知行编程网 隐藏边栏  14 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python字符串方法format()如何使用的相关知识,包括字符串python,以及python正则表达式这些编程知识,希望对大家有参考作用。

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

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

2、转换标志:感叹号后面的字表示给定的值转换成相应的格式。

格式说明符:冒号后面的表达式用于详细指定字符串的格式。


实例

>>> # 指定表示方式
>>> 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


本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享