当前位置: 移动技术网 > IT编程>脚本编程>Python > Python字符串的格式化,看这一篇就够了

Python字符串的格式化,看这一篇就够了

2019年03月26日  | 移动技术网IT编程  | 我要评论

猪八戒异界游,uukxw,海南天气预报查询一周

知识星球

相信很多人在格式化字符串的时候都用"%s" % v的语法,pep 3101 提出一种更先进的格式化方法 str.format() 并成为 python 3 的标准用来替换旧的 %s 格式化语法,cpython 从 2.6 开始已经实现了这一方法(其它解释器未考证)。

format()

新的 format() 方法其实更像是一个简略版的模板引起(template engine),功能非常丰富。

模板中替换变量用 {} 包围,且由 : 分为两部分,其中后半部分 format_spec 在后面会单独讨论。

前半部分有三种用法:

  • 代表位置的数字
  • 代表keyword的标识符

这与函数调用的参数类别是一致的

print("{} {}".format("hello", "world"))
# 等同于以下几种
print("{0} {1}".format("hello", "world"))
print("{hello} {world}".format(hello="hello", world="world"))
print("{0}{1}{0}".format("h", "e"))

# hello world
# hello world
# hello world
# heh

除此之外,就像函数参数的解包一样,format() 中也可以直接使用解包操作

print("{author}.{city}".format(**{"author": "miracle", "city": "上海"}))
print("{} {}".format(*["miracle", "上海"]))

miracle.上海
miracle 上海

在模板中还可以通过 .identifier 和 [key] 的方式获取变量内的属性或值(需要注意的是 "{}{}" 相当于 "{0}{1}")

data = {'author': 'miracle', 'like': 'papapa'}
print("author: {0[author]}, like: {0[like]}".format(data))
langs = ["python", "ruby"]
print("{0[0]} vs {0[1]}".format(langs))

print("\n====\nhelp(format):{.__doc__}".format(str.format))

# name: python, score: 100
# python vs ruby

# ====
# help(format):
#  s.format(*args, **kwargs) -> str

强制转换,可以通过 ! + r|s|a 的方式对替换的变量进行强制转换

  • "{!r}" 对变量调用 repr()
  • "{!s}" 对变量调用 str()
  • "{!a}" 对变量调用 ascii()

冒号之后的部分定义输出的样式

align 代表对齐方向,通常要配合 width 使用,而 fill 则是填充的字符(默认为空白):

for align, text in zip("<^>", ["left", "center", "right"]):
   # 务必看懂这句话
   print("{:{fill}{align}16}".format(text, fill=align, align=align))

print("{:0=10}".format(100)) # = 只允许数字

# left<<<<<<<<<<<<
# ^^^^^center^^^^^
# >>>>>>>>>>>right
# 0000000100

同时可以看出,样式设置里面可以嵌套 {} ,但是必须通过 keyword 指定,且只能嵌套一层。

接下来是符号样式:+|-|' ' 分别指定数字是否需要强制符号(其中空格是指在正数的时候不显示 + 但保留一位空格)

print("{0:+}\n{1:-}\n{0: }".format(3.14, -3.14))

# +3.14
# -3.14
# 3.14

用于表示特殊格式的数字(二进制、十六进制等)是否需要前缀符号

逗号也是用于表示数字时是否需要在千位处进行分隔

0 相当于前面的{:0=} 右对齐并用 0 补充空位

print("binary: {0:b} => {0:#b}".format(3))
print("large number: {0:} => {0:,}".format(1.25e6))
print("padding: {0:16} => {0:016}".format(3))

# binary: 11 => 0b11
# large number: 1250000.0 => 1,250,000.0
# padding:                3 => 0000000000000003

最后小胖给大家介绍一下熟悉的小数点精度问题, .n 和格式化类型。

这里仅给出一些示例,详细内容可以查阅文档:

from math import pi
print("pi = {pi:.2}, also = {pi:.7}".format(pi=pi))

# pi = 3.1, also = 3.141593

integer

for t in "b c d #o #x #x n".split():
   print("type {0:>2} of {1} shows: {1:{t}}".format(t, 97, t=t))

# type  b of 97 shows: 1100001
# type  c of 97 shows: a
# type  d of 97 shows: 97
# type #o of 97 shows: 0o141
# type #x of 97 shows: 0x61
# type #x of 97 shows: 0x61
# type  n of 97 shows: 97

float

for t, n in zip("eeffggn%", [12345, 12345, 1.3, 1.3, 1, 2, 3.14, 0.985]):
   print("type {} shows: {:.2{t}}".format(t, n, t=t))

# type e shows: 1.23e+04
# type e shows: 1.23e+04
# type f shows: 1.30
# type f shows: 1.30
# type g shows: 1
# type g shows: 2
# type n shows: 3.1
# type % shows: 98.50%

string (default)

try:
   print("{:s}".format(123))
except:
   print("{}".format(456))

# 456

关注公众号「python专栏」,后台回复「腾讯架构资源1」,获取由腾讯架构师整理的大数据学习全套资源包!

python专栏二维码

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网