5.1 整数的进制输出
print('%s'%'hello world')
>hello world
print('%o'%20) # 八进制输出
>24
print('%d'%20) # 十进制输出
>20
print('%x'%20) # 十六进制输出
>14
5.2 浮点数输出
print('%.3f' % 3.1415926) # 保留3位小数位
>3.142
print('%.3e' % 3.1415926) # 保留3位小数位,使用科学计数法,且指数输出
>3.142e+00
print('%.3g' % 3.1415926) # 保留3位有效数字
>3.14
## round(x,n)函数四舍五入
print(round(1.1135,3)) # 取3位小数,由于3为奇数,则向下“舍”
>1.13
print(round(1.1145,3)) # 取3位小数,由于4为偶数,则向上“入”
>1.15
5.3 字符串输出
print('%20s' % 'hello world') #右对齐,取20位,不够则补位
> hello world
print('%20s' % 'hello world') #左对齐,取20位,不够则补位
>hello world
print('%-10.2s' % 'hello world') # 左对齐,10位占位符,取2位
>he
print('%10.2s' % 'hello world') # 右对齐,10位占位符,取2位
> he
print('%.2s' % 'hello world') # 左对齐,10位占位符,取2位
>he
5.4 format
## 基本用法:使用大括号‘{}’作为特殊字符代替‘%’,使用方法由两种:b.format(a)和format(a,b)
print('{} {}'.format('hello','world')) # 不带字段
>hello world
print('{1} {0}'.format('hello','world')) # 带数字编号,可调换顺序
>world hello
print('{a} {b} {a}'.format(a='hello',b='world')) # 带数字编号,可调换顺序
>hello world hello
## 进阶用法:(1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐;(2)取位数“{:4s}”、"{:.2f}"等
print("{:=>30,.2f}".format(12345.6789))
>>=====================12,345.68
: <填充> <对齐> <宽度> <,> < . 精度> <类型> 引导符号 用于填充的单个字符 < 左对齐 宽度 千位分隔符 浮点数小数精度或字符串最大输出长度 整数类型(b, c, d, o, x, X)浮点数类型(e, E, f, %)
print('{0:b}'.format(3)) ##二进制输出
print('{:c}'.format(80)) ##转化为unicode字符串
print('{:d}'.format(20)) ##十进制输出
print('{:o}'.format(20)) ##八进制输出
print('{:x}'.format(20)) ##十六进制输出
print('{:e}'.format(20)) ##幂符号输出
print('{:%}'.format(20)) ##%输出
print('转化为华氏温度为{:.2f}F'.format(54)) ##带固定内容(F)的输出格式
>11
>P
>20
>24
>14
>2.000000e+01
>2000.000000%
>转化为华氏温度为54.00F
5.5 温度转换代码
T = input('请输入带单位的温度(t/f):')
if T[-1] in ['f','F']:
C = (eval(T[0:-1])-32)/1.8 ## eval() 函数转化字符串为其他格式,即去掉引号
print("转化为摄氏温度为{:.2f}C".format(C)) ## 格式化输出
elif T[-1] in ['c','C']:
F =1.8*eval(T[0:-1]) +32
print("转化为华氏温度为ty{:.2f}F".format(F))
else:
print('您的输入有误')