• 技术文章 >Python技术 >Python基础教程

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

    宋雪维宋雪维2020-12-19 11:57:43原创3098

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

    1、str.format() 方法

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

    2、基本语法

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

    3、基本用法

    1

    2

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

    We are the knights who say "Ni!"

    4、具体使用实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    '{:b}'.format(11)

     

    '{:d}'.format(11)

     

    '{:o}'.format(11)

     

    '{:x}'.format(11)

     

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

     

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

    输出

    1

    2

    3

    4

    5

    6

    1011

    11

    13

    b

    0xb

    0XB

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

    专题推荐:pythonstrformat方法​
    上一篇:python rjust函数用法 下一篇:python中zfill方法如何设置字符串?

    相关文章推荐

    • Python find()函数是什么• python ljust对字符串限制• python rjust函数用法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网