您现在的位置是:课程教程文章

如何使用python中str.format() 方法​?

2023-12-15 21:49课程教程文章 人已围观

在python中,我们一般使用%和format用于格式化输出。其实还有一种方式,那就是str.format() 方法,它可以包含用大括号{}分隔的文本或替换字段。

1、str.format() 方法

通过字符串中的花括号 {} 来识别替换字段 replacement field,从而完成字符串的格式化。

2、基本语法

通过 {} 和 : 来代替以前的 %,即接收的参数不需限制数据类型。

3、基本用法

>>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
We are the knights who say "Ni!"

4、具体使用实例

'{:b}'.format(11)

'{:d}'.format(11)

'{:o}'.format(11)

'{:x}'.format(11)

'{:#x}'.format(11)

'{:#X}'.format(11)

输出

1011
11
13
b
0xb
0XB

对齐文本并指定特定的宽 以上就是python中str.format() 方法的介绍,希望能对你有所帮助哟~

课程教程:如何使用python中str.format() 方法​?

上一篇:python中zfill方法如何设置字符串?

下一篇:没有了

站点信息

  • 文章统计篇文章