python的格式化输出(%用法和.format()用法)

%用法
1、整数输出
%o 八进制输出
%d 十进制输出
%x 十六进制输出

2、浮点数输出
(1)格式化输出
%f ——保留小数点后面六位有效数字
  %.3f,保留3位小数位
%e ——保留小数点后面六位有效数字,指数形式输出
  %.3e,保留3位小数位,使用科学计数法
%g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
  %.3g,保留3位有效数字,使用小数或科学计数法

(2)内置round()
round(number[, ndigits])
参数:
number - 这是一个数字表达式。
ndigits - 表示从小数点到最后四舍五入的位数。默认值为0。
返回值
该方法返回x的小数点舍入为n位数后的值。

round()函数只有一个参数,不指定位数的时候,返回一个整数,而且是最靠近的整数,类似于四舍五入,当指定取舍的小数点位数的时候,一般情况也是使用四舍五入的规则,但是碰到.5的情况时,如果要取舍的位数前的小数是奇数,则直接舍弃,如果是偶数则向上取舍。

3、字符串输出
%s
%10s——右对齐,占位符10位
%-10s——左对齐,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取两位字符串

4、多类输入一起输入
“%d%f" % (a, b)

format用法
相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

位置匹配

(1)不带编号,即“{}”

(2)带数字编号,可调换顺序,即“{1}”、“{2}”

(3)带关键字,即“{a}”、“{tom}”

复制代码
1 >>> print(’{} {}’.format(‘hello’,‘world’)) # 不带字段
2 hello world
3 >>> print(’{0} {1}’.format(‘hello’,‘world’)) # 带数字编号
4 hello world
5 >>> print(’{0} {1} {0}’.format(‘hello’,‘world’)) # 打乱顺序
6 hello world hello
7 >>> print(’{1} {1} {0}’.format(‘hello’,‘world’))
8 world world hello
9 >>> print(’{a} {tom} {a}’.format(tom=‘hello’,a=‘world’)) # 带关键字
10 world hello world

格式转换
‘b’ - 二进制。将数字以2为基数进行输出。
‘c’ - 字符。在打印之前将整数转换成对应的Unicode字符串。
‘d’ - 十进制整数。将数字以10为基数进行输出。
‘o’ - 八进制。将数字以8为基数进行输出。
‘x’ - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
‘e’ - 幂符号。用科学计数法打印数字。用’e’表示幂。
‘g’ - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
‘n’ - 数字。当值为整数时和’d’相同,值为浮点数时和’g’相同。不同的是它会根据区域设置插入数字分隔符。
‘%’ - 百分数。将数值乘以100然后以fixed-point(‘f’)格式打印,值后面会有一个百分号。

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)  # 在前面加“#”,则带进制前缀
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

设置参数输出:

print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

format()的变形应用

# a.format(b)
>>> "{0} {1}".format("hello","world")
'hello world'


# f"xxxx"
# 可在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式:

>>> a = "hello"
>>> b = "world"
>>> f"{a} {b}"
'hello world'



name = 'jack'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99

print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')

# 结果
my name is Jack.
I am ****18**** years old.
I am a man
My salary is   9999.990

猜你喜欢

转载自blog.csdn.net/weixin_42999937/article/details/82888139