python 学习 笔记 format 用法

来源:互联网 发布:算法的概念简单例题 编辑:程序博客网 时间:2024/04/30 06:19

  习惯了用 print ‘%s’ 这种结构来格式化输出, 今天无意中看到python 有format函数,读了一遍它的帮助文档。使用起来还是比较方便的。 摘录出来。


# 基本的按顺序输出 python版本需要2.7以上>>> '{0} {1} {2}'.format('a', 'b', 'c')'a b c'# 输出顺序可以调整>>> '{1} {0} {2}'.format('a', 'b', 'c')'b a c'# 右对其保留位置用其他字符代替空格# * 用星号填充空格# > 右对齐# 30 保留三十位置 >>> '{:*>30}'.format('right aligned test')'************right aligned test'# 字符居中>>> '{:*^36}'.format('fillwithstart')'***********fillwithstart************'# 各种数字进制显示>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:#b}".format(15)'int: 15;  hex: f;  oct: 17;  bin: 0b1111'


0 0