美文网首页
【Python】 str.format()字符串格式化

【Python】 str.format()字符串格式化

作者: ItchyHiker | 来源:发表于2018-11-25 14:25 被阅读0次

str.format()是在python3中引入的字符串格式化方法,可以用来对字符串输出进行替换。其语法格式为:

{}.format(value)

例如单个字符串替换:

In [1]: print("{}, Is anybody in there?".format("hello"))
hello, Is anybody in there?

多个字符串替换,为顺序替换:

In [3]: print("{}, is anybody in {}".format("hello", "there"))
hello, is anybody in there

在{}里面定义使用format中值的顺序:

In [2]: print("{1} is an, {0}".format("ItchyHacker", "AI"))
AI is an, ItchyHacker

str中第一个{}为1, 第二个为0, 因此分别对应为"AI"和”ItchyHacker"
在{}中第一个替换值的key,并且在format中通过key指定值。

In [5]: print("{name} is an, {obj}".format(name="ItchyHacker", obj="AI"))
ItchyHacker is an, AI

通过在{}中使用占位符对输出进行定制:
输出数据类型的指定:

s – strings
d – decimal integers (base-10)
f – floating point display
c – character
b – binary
o – octal
x – hexadecimal with lowercase letters after 9
X – hexadecimal with uppercase letters after 9
e – exponent notation

例如:

In [7]: print("{name:s} is {height:f}m high, and weights {weight:d}kg".format(name="
   ...: ItchyHacker", height=1.75, weight=70))
ItchyHacker is 1.750000m high, and weights 70kg

指定输出的长度和使用占位符号:

数字:  输出占多少位
.数字: 保留小数点多少位
0数字: 以0为占位符号

身高用.2f限制输出小数点后两位,体重使用04d限制输出4位,同时使用0为占位符号。没有0的话就是空格作为占位符号。

In [8]: print("{name:s} is {height:.2f}m high, and weights {weight:04d}kg".format(na
   ...: me="ItchyHacker", height=1.75, weight=70))
ItchyHacker is 1.75m high, and weights 0070kg

指定对齐方式:

<   :  left-align text in the field
^   :  center text in the field
>   :  right-align text in the field

体重右边对齐:

In [9]: print("{name:s} is {height:.2f}m high, and weights {weight:>6d}kg".format(na
   ...: me="ItchyHacker", height=1.75, weight=70))
ItchyHacker is 1.75m high, and weights     70kg

相关文章

  • 字符串的格式化操作

    旧式字符串格式化%运算符,位置格式化(python2) str.format字符串格式化(python3,它存在一...

  • Python 标准化输出

    一、 str.format() Python2.6 开始,新增了一种格式化字符串的函数 str.format()...

  • 013.Python格式化

    Python格式化 1. 概述 Python2.6 开始,新增了一种格式化字符串的函数 str.format(),...

  • 详解Python中str.format()格式化函数

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本...

  • Python format 格式化函数

    Python2.6 开始,新增了一种格式化字符串的函数str.format(),它增强了字符串格式化的功能。 基本...

  • python format格式化函数用法

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。 基...

  • format函数

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。 基...

  • python输出格式化

    1)Python2.6 开始,新增了一种格式化字符串的函数str.format(),它增强了字符串格式化的功能。 ...

  • python字符串的format方法

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。 基...

  • Python6 字符串:格式化

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。 1...

网友评论

      本文标题:【Python】 str.format()字符串格式化

      本文链接:https://www.haomeiwen.com/subject/ofspqqtx.html