Python格式化
参考:《Python3程序开发指南 第二版》
%格式化
基本使用
s = "name: %s, age: %d, weight: %fkg" % ("Tom", 20, 60.5)
print(s) # name: Tom, age: 20, weight: 60.500000kg
s = "name: %(name)s, age: %(age)d, weight: %(weight)fkg" % {
"name": "Tom", "age": 20, "weight": 60.5
}
print(s) # name: Tom, age: 20, weight: 60.500000kg
# %转换
# print("%s,%"%("Tom")) ValueError: incomplete format
print("%s,%%"%("Tom")) # Tom,%
print("%s,%") # %s,%
print("%s,%%") # %s,%%
字符串格式规约
# 字符串格式规约方法 [-] minwidth .maxwidth [s|r|a]
s = "The sword of truth"
# .maxwidth指定最大宽度
print("[%.10s]" % (s)) # [The sword ]
# 默认右对齐,添加-左对齐
print("%25s, %-25s," % (s, s)) # [ The sword of truth] [The sword of truth ]
# s是字符串形式,r是表象形式
# a是ascii的表象形式,字符使用7比特表示,否则使用最短的\xhh,\uhhhh或\Uhhhhhhhh
import decimal
print("%s %r %a" % (decimal.Decimal("93.4"),
decimal.Decimal("93.4"),
decimal.Decimal("93.4"))) # 93.4 Decimal('93.4') Decimal('93.4')
# 你好,世界 '你好,世界' '\u4f60\u597d\uff0c\u4e16\u754c'
print("%s %r %a" % ("你好,世界", "你好,世界", "你好,世界"))
整数格式规约
# 整数规约方法 [-] [+] # 0 minwidth
# 默认右对齐,添加-左对齐,左对齐不会0填充
print("[%012d], [%-012d]"%(-8749203,-8749203)) # [-00008749203], [-8749203 ]
# +号正数强制添加符号
print("[%+012d], [%012d]"%(8749203,8749203)) # [+00008749203], [000008749203]
# d十进制,o八进制,x小写十六进制,X大写十六进制,c对应字符
print("%d,%o,%x,%X,%c"%(255,255,255,255,255)) # 255,377,ff,FF,ÿ
# o,x,X可以添加#增加进制前导符号
print("%#d,%#o,%#x,%#X,%#c"%(255,255,255,255,255)) # 255,0o377,0xff,0XFF,ÿ
浮点数格式规约
# 与整数基本一样,只是有两个差别
# 添加了.precision控制小数点的位数
# e小写字母指数形式,E大写字母指数形式,f标准浮点,g和G数字小的时候与f相同,大的时候与e和E相同
amount = (10 ** 3) * math.pi
# [ 3.14e+03], [ 3141.59], [ 3.1E+03]
print("[%12.2e], [%12.2f], [%12.2G]"%(amount,amount,amount))
str.format()格式化
基本使用
可以使用字符串的format()方法返回格式化后的字符串,format的字符串基本形式为:
# {field_name}
# {field_name!conversion}
# {field_name:format_specification}
# {field_name!conversion:format_specification}
- 使用位置参数
# The novel 'Hard Times' was published in 1854
print("The novel '{0}' was published in {1}".format("Hard Times", 1854))
- 大括号的转义
# {I'm in braces} I'm not {}
print("{{{0}}} {1} {{}}".format("I'm in braces", "I'm not"))
- 使用关键字参数
# She turned 88 this year
print("{who} turned {age} this year".format(who="She", age=88))
- 混合使用位置参数和关键字参数
# 关键字参数总在位置参数之后
# The boy was 12 last week
print("The {who} was {0} last week".format(12, who="boy"))
- 使用序列
stocks = ["paper", "envelopes", "notepads", "pens", "paper clips"]
# We have envelopes and notepads in stock
print("We have {0[1]} and {0[2]} in stock".format(stocks))
- 使用字典
d = {"animal": "elephant", "weight": 12000}
# 字符串里的键不用引号
# The elephant weighs 12000kg
print("The {0[animal]} weighs {0[weight]}kg".format(d))
- 使用属性
import sys
import math
# math.pi == 3.141592653589793, sys.maxunicode == 1114111
print("math.pi == {0.pi}, sys.maxunicode == {1.maxunicode}".format(math, sys))
- 忽略字段名
# Python can count
print("{} {} {}".format("Python", "can", "count")) # Python3.1起
- 使用序列拆分
# 1 2 1
print("{0} {1} {0}".format(*[1, 2, 3]))
- 使用映射拆分
# 只有最后一个参数可以使用映射拆分
# 10
print("{x}".format(**{"x": 10, "y": 20}))
# 10,1,2,1
print("{x},{0},{1},{0}".format(*[1, 2, 3], **{"x": 10, "y": 20}))
- 字符串形式转换
# s是字符串形式,r是表象形式
# a是ascii的表象形式,字符使用7比特表示,否则使用最短的\xhh,\uhhhh或\Uhhhhhhhh
# 93.4 93.4 Decimal('93.4') Decimal('93.4')
print("{0} {0!s} {0!r} {0!a}".format(decimal.Decimal("93.4")))
# 你好,世界 你好,世界 '你好,世界' '\u4f60\u597d\uff0c\u4e16\u754c'
print("{0} {0!s} {0!r} {0!a}".format("你好,世界"))
字符串格式规约
# 字符串的格式规约 : fill[填充] align[对齐] miniwidth[最小宽度] .maxwidth[最大宽度]
s = "The sword of truth"
# 没有指定填充字符默认为空格,<左对齐,>右对齐,^中间对齐
# [The sword of truth , The sword of truth, The sword of truth ]
print("[{0:<25}, {0:>25}, {0:^25}]".format(s))
# 指定了填充字符必须指定对齐字符
# [The sword of truth-------, -------The sword of truth, ---The sword of truth----]
print("[{0:-<25}, {0:->25}, {0:-^25}]".format(s))
# 格式规约内部可以包含替换字段
# [The sword ]
print("[{0:.{1}}]".format(s, 10))
整数格式规约
# 整数格式规约 : fill align sign # 0 minwidth , type(b c d n o x X)
# 0填充,fill align的形式=会将符号提前,其他的不会提前,0规约符号会提前
# [-87492030000,0000-8749203,00-874920300,-00008749203,-00008749203]
print("[{0:0<12},{0:0>12},{0:0^12},{0:0=12},{0:012}]".format(-8749203))
# sign的选项+ - " "
# [+0500,-0500]
print("[{0:0=+5},{1:0=+5}]".format(500, -500))
# [00500,-0500]
print("[{0:0=-5},{1:0=-5}]".format(500, -500))
# [ 0500,-0500]
print("[{0:0= 5},{1:0= 5}]".format(500, -500))
# ,分组
# ****2,394,321
print("{0:*>13,}".format(2394321))
# type
# b二进制,o八进制,x小写十六进制,X大写十六进制,可以加#号叫上前导
# d十进制,c对应的unicode字元,不能加#
# 00000000000011111111, 377, ff, FF, 255, ÿ
print("{0:020b}, {0:o}, {0:x}, {0:X}, {0:d}, {0:c}".format(255))
# 0b000000000011111111, 0o377, 0xff, 0XFF, 255, ÿ
print("{0:#020b}, {0:#o}, {0:#x}, {0:#X}, {0:d}, {0:c}".format(255))
# n以场所敏感的方式输出数字,对整数默认d效果,对浮点数默认g效果,默认C场所
import local
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
# 123,456 1,234.56
print("{0:n} {1:n}".format(123456, 1234.56))
locale.setlocale(locale.LC_ALL, "de_DE.UTF-8")
# 123.456 1.234,56
print("{0:n} {1:n}".format(123456, 1234.56))
locale.setlocale(locale.LC_ALL, "C")
# 123456 1234.56
print("{0:n} {1:n}".format(123456, 1234.56))
浮点数格式规约
# 浮点数格式规约浮点数格式规约与整数一样,只是有两个差别
# 可以指定精度(小数点后跟随的数字个数)
# type指定e小写字母指数形式,E大写字母指数形式,f标准浮点
# g和G数字小的时候与f相同,大的时候与e和E相同,%百分比形式
amount = (10 ** 3) * math.pi
# [ 3.14e+03, 3141.59, 3.1e+03]
print("{0:12.2e}, {0:12.2f}, {0:12.2g}".format(amount))
# [ 3.14E+03, 314159.27%, 3.1E+03]
print("{0:12.2E}, {0:12.2%}, {0:12.2G}".format(amount))
f-string格式化
基本使用
f-string
是Python3.6新引入的一种字符串格式化方法。
- 基本形式
# {field_name}
# {field_name!conversion}
# {field_name:format_specification}
# {field_name!conversion:format_specification}
- 使用字面量
# She turned 88 this year
print(f"{'She'} turned {88} this year")
- 使用变量
who = "She"
age = 88
# She turned 88 this year
print(f"{who} turned {age} this year")
- 使用序列
l = ["She",88]
# She turned 88 this year
print(f"{l[0]} turned {l[1]} this year")
- 使用字典
d = {"who":"She","age":88}
# She turned 88 this year
print(f"{d['who']} turned {d['age']} this year")
- 使用属性
import math
# math.pi == 3.141592653589793
print(f"math.pi == {math.pi}")
- 使用表达式
age = 18
# Age: 19, weight:65000.0g
print(f"Age: {age+1}, weight:{65.0*1000}g")
- 使用函数
# 2**2 = 4
print(f"2**2 = {pow(2,2)}")
- 大括号转义
a = "I'm in braces"
b = "I'm not"
# {I'm in braces} I'm not {}
print(f"{{{a}}} {b} {{}}")
\
转义
# 大括号里不允许出现`\`符号
# print(f"{'\u20ac'}") SyntaxError: f-string expression part cannot include a backslash
# 使用变量的形式解决
s = '\u20ac'
# €
print(f"{s}")
- 字符串形式转换
# s是字符串形式,r是表象形式
# a是ascii的表象形式,字符使用7比特表示,否则使用最短的\xhh,\uhhhh或\Uhhhhhhhh
test = decimal.Decimal("93.4")
# 93.4 93.4 Decimal('93.4') Decimal('93.4')
print(f"{test} {test!s} {test!r} {test!a}")
test = "你好世界"
# 你好世界 你好世界 '你好世界' '\u4f60\u597d\u4e16\u754c'
print(f"{test} {test!s} {test!r} {test!a}")
格式规约
格式规约方法与str.format()格式化方法的格式规约方法基本一致