Python 格式化输出

– Start

点击此处观看本系列配套视频。


Python 提供了下面几种格式化的方式。

f 字符串

语法

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>
format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

例子

name = 'zhangsan'
age = 30
salary = 8888.888


#------------------ [field_name]
print(f'name is {name}')                            # field_name 可以是 name
print(f'the class of name is {name.__class__}')     # field_name 可以是 name 的属性
print(f'the uppercase of sname is {name.upper()}')  # field_name 可以是 name 的方法
print(f'the first letter of name is {name[0]}')     # field_name 可以是 name[0]


#------------------ ["!" conversion]
print(f'name={name!s}')  # 调用 str(),将 name 转成可打印字符串
print(f'name={name!r}')  # 调用 repr(),将 name 转成可打印字符串
print(f'name={name!a}')  # 调用 ascii(),将 name 转成可打印字符串


#------------------ [":" format_spec]
print(f'salary={salary:,.2f}') # 逗号表示千分位,.2表示保留2位小数,f表示格式化浮点数
print(f'{age:*>+30d}') # +1234*************************

str.format 方法

format 方法的语法和 f 字符串一样,下面是一些简单的例子。

name = 'zhangsan'
age = 30
salary = 8888.888


#------------------ [field_name]
print('name={}, age={}'.format(name, age))       # 根据参数默认位置
print('name={1}, age={0}'.format(age, name))     # 指定参数位置
print('name={n}, age={a}'.format(n=name, a=age)) # 根据关键字

print('the class of name is {0.__class__}'.format(name))     # 根据参数位置访问属性
print('the class of name is {n.__class__}'.format(n=name))   # 根据参数关键字访问属性

print('the first letter of name is {0[0]}'.format(name))     # 根据参数位置访问
print('the first letter of name is {n[0]}'.format(n=name))   # 根据参数关键字访问


#------------------ ["!" conversion]
print('name={n!s}'.format(n=name))  # 调用 str(),将 name 转成可打印字符串
print('name={n!r}'.format(n=name))  # 调用 repr(),将 name 转成可打印字符串
print('name={n!a}'.format(n=name))  # 调用 ascii(),将 name 转成可打印字符串


#------------------ [":" format_spec]
print('salary={s:,.2f}'.format(s=salary)) # 逗号表示千分位,.2表示保留2位小数,f表示格式化浮点数
print('{a:*>+30d}'.format(a=age)) # +1234*************************

format 函数

salary = 8888.888
age = 30

# 第二个参数是能提供值
print(format(salary, ',.2f')) # 逗号表示千分位,.2表示保留2位小数,f表示格式化浮点数
print(format(age, '*>+30d')) # +1234*************************

Formatter 类

Formatter 类的语法和 f 字符串一样,下面是一些简单的例子。

from string import Formatter

# 定义 Formatter
formatter = Formatter()
name = 'zhangsan'
age = 30
salary = 8888.888


#------------------ [field_name]
print(formatter.format('name={}, age={}', name, age))       # 根据参数默认位置
print(formatter.format('name={1}, age={0}', age, name))     # 指定参数位置
print(formatter.format('name={n}, age={a}', n=name, a=age)) # 根据关键字

print(formatter.format('the class of name is {0.__class__}', name))     # 根据参数位置访问属性
print(formatter.format('the class of name is {n.__class__}', n=name))   # 根据参数关键字访问属性

print(formatter.format('the first letter of name is {0[0]}', name))     # 根据参数位置访问
print(formatter.format('the first letter of name is {n[0]}', n=name))   # 根据参数关键字访问


#------------------ ["!" conversion]
print(formatter.format('name={n!s}', n=name))  # 调用 str(),将 name 转成可打印字符串
print(formatter.format('name={n!r}', n=name))  # 调用 repr(),将 name 转成可打印字符串
print(formatter.format('name={n!a}', n=name))  # 调用 ascii(),将 name 转成可打印字符串


#------------------ [":" format_spec]
print(formatter.format('salary={s:,.2f}', s=salary)) # 逗号表示千分位,.2表示保留2位小数,f表示格式化浮点数
print(formatter.format('{a:*>+30d}', a=age)) # +1234*************************

printf 风格

printf 是经典的格式化方法,几乎每种语言都支持。Python 没有 printf 函数,但是它也支持 printf 风格格式化,只是不推荐使用,下面是一个简单的例子。

s = 'a'

print('%(x)s'%{'x':s})
print('%(x).2f'%{'x':1234.222})

Template

Template 使用 shell 和 perl 等脚本语言的方式。

from string import Template

name = 'zhangsan'
age = 30
salary = 8888.888


s = Template('$n is $a years old and his salary is $s').substitute(n=name, a=age, s=salary)
print(s)

手动格式化

通常我们不会用手动的方式,下面是一个简单的例子。

import math

def my_print(n):
    print(str(n).ljust(7) + str(math.ceil(n)).ljust(7) + str(math.floor(n)).ljust(7) + str(round(n)).ljust(7) + str(math.trunc(n)).ljust(7))


print('NUM    CEIL   FLOOR  ROUND  TRUNC')
my_print(5.5)
my_print(2.5)
my_print(1.6)
my_print(1.1)
my_print(1)
my_print(-1)
my_print(-1.1)
my_print(-1.6)
my_print(-2.5)
my_print(-5.5)

– 更多参见:Python 精萃
– 声 明:转载请注明出处
– Last Updated on 2018-09-26
– Written by ShangBo on 2018-08-20
– End

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值