python_test_0503

# 格式化字符串--P45
format2 = "Pi with three decimals:%.3f"
from math import pi

print(format2 % pi)
# 字符串模板
from string import Template

s = Template('$x,glorious $x!')
value = s.substitute(x='txwtech')  # 替换了x变量的值
print(value)
s2 = Template("${x}nice")  # 替换的内容与现有内容相连,挨着一起,就添加{}
value2 = s2.substitute(x="ok")
print(value2)
# 插入美元符号$
s3 = Template("make $$ selling $x")
value3 = s3.substitute(x="oo")
print(value3)
# 字典变量
s5 = Template('a $thing muse never $action')
d = {}
d['thing'] = 'gentleman'
d['action'] = 'show his talent'
value5 = s5.substitute(d)
print(value5)
#字符串格式化完整版本
s6 = '%s plus %s is %s' %(1,2,3)
print(s6)
s7 = 'Price of eggs:$%d' %32
print(s7) #打印十进制
s8 = 'Hexadecimal price of eggs %x' %42
print(s8) #打印十六进制,2a
#打印浮点数
from math import pi
s9 = 'pi:%f...' % pi
print(s9)
# %i带符号十进制数
s10 = 'very inexact estimate of pi: %i' % pi
print(s10)
s11 = 'using str: %s' % 41
print(s11)
s12 = 'using str2:%r' % 32
print(s12)
#字符串宽度与精度
f1 = '%10f' % pi #输出总数10位数,两个空格+3.141593
print(f1)
f2 = '%10.2f' %pi
print(f2) #小数点两位,位数不够,前面添加空格
f3 = '%.2f' %pi #默认宽度,小数2位
print(f3)
#取字符串宽度5
f5 = '%.5s' % 'likee is ok'
print(f5)
#林外一种方式,使用星号(元组参数)
f6 = '%.*s' %(5,'beautiful')
print(f6)
#符号对齐用0填充
f7 = '%010.2f' % pi
print(f7)
#减号(-)用来左对齐数值
f8 = '%-10.2f' % pi
print(f8)
print(('%5d' % 10) +'\n' +('%5d' % -10))
#加号标注+-符号
print(('%+5d' % 10) +'\n' +('%+5d' % -10))
#3-1
width = 20
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format ='%-*s%*.2f'
print('='*width)
print (header_format %(item_width,'Item',price_width,'Price'))
print('-'*width)
print(format %(item_width,'Apples',price_width,0.4))
print(format %(item_width,'Pears',price_width,0.5))
print(format %(item_width,'Cantaloupes',price_width,1.92))
print(format %(item_width,'Dried',price_width,8))
print(format %(item_width,'Prunes',price_width,12))
print('='*width)
print('PP49')

 

posted @ 2023-05-28 15:45  txwtech  阅读(11)  评论(0编辑  收藏  举报