python 第三周(20201121) fomat用法大全、模块调用

博主分享了在Python学习中遇到的困难,主要聚焦于format字符串格式化和模块调用。format用法虽然易懂,但在实际操作中存在一定挑战。同时,博主预告将深入探讨Python的模块系统。

最近太忙了,功课稍微落下一些。
而且还碰到forma知识点,头大的要死。容易理解,但是写起来很头疼。
初步接触到模块,得好好研究研究。

"""
".fomat关键知识点
^,<,>分别是居中、左对齐、右对齐,后面带宽度,:号后面带填充的字符,只能是一个字
符,不指定则默认是用空格填充。
+表示在正数前显示+,负数前显示- ,(空格)表示在正数前加空格
"""
print('========基于字典的字符串格式化============')
print('%(n)d%(x)s'%{'n':1,'x':'spam'})
#打印结果: 1spam

print('========调用整个字典模块,基于键引用的格式化表达式一次性替换============')
reply = """
Greetings...
Hello %(name)s!
Your age squared is %(age)s
"""
values ={'name':'Bob','age':40}
print(reply%values)

print('========调用整个字典模块,内置函数vars,包含在本函数所有在本函数调用时存在的变量============')
food ='spam'
age =40
print(vars())#调用所有在本函数调用时存在的变量

food ='spam'
age =40
s1='%(age)d %(food)s' % vars()
print(s1)

print('========字符串格式化调用方法,基础知识============')
template = '{0},{1} and {2}' #依赖于位置定位
print(template.format('spam','ham','eggs'))

template1 = '{motto},{pork} and {food}!' #依赖于关键字定位
print(template1.format(motto='spam',pork='ham',food='eggs'))

template2 ='{motto},{0} and {food}?'
print(template2.format('ham',motto='spam',food='eggs'))

s2= '{motto},{0}and{food}。'.format(42,motto=3.14,food=[1,2])
print('s2值为:',s2)
s3= '{motto},{0} and {food}'.format(42,motto=3.14,food=[1,2]) #增加空格
print('s3值为:',s3)
s4 = s3.split('and')
print('s4值为:',s4)
s5 = s3.replace('and','but under no circumstances')
print('s5值为:',s5)

#打印结果为以下:会严格按照 ‘’ 里面所有格式打印 包括 空格
# ========字符串格式化调用方法,基础知识============
# spam,ham and eggs
# spam,ham and eggs
# spam,ham and eggs
# s2值为: 3.14,42and[1, 2]
# s3值为: 3.14,42 and [1, 2]
# s4值为: ['3.14,42 ', ' [1, 2]']
# s5值为: 3.14,42 but under no circumstances [1, 2]

print('========添加键、属性和偏移量,fomat()要点不受顺序限制===========')
import sys
print('My {1[spam]} runs {0.platform}'.format(sys,{'spam':'laptop'}))

somelist = list('SPAM')
print(somelist)
s7= 'first={0[0]},third={0[2]}'.format(somelist)
print('s7为:',s7)
s8= 'first={0[0]},last={1}'.format(somelist[0],somelist[-1]) #分开定位,-1定位最后1位
print('s8为:',s8)
parts = somelist[0],somelist[-1],somelist[1:3]
s9= 'first={0},last={1},middle={2}'.format(*parts) #为何加*part,标准定位0-1-2  *parts 多次调用
# 要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可
# 要点:关键字参数值要对得上,可用列表当关键字参数传入值,字典前加*即可
print('s9为:',s9)
# **format函数可以接受不限个参数,位置可以不按顺序。
s10='{}{}'.format('hello','world') #不指定顺序,按默认顺序
s11='{0}{1}'.format("hello","world")#设置指定位置
s12='{1}{0}{1}'.format("hello","world")#设置指定位置
print("s10,s11,s12分别为:",s10,s11,s12)

# """
# 3.1415926{:2}f3.14保留小数点后两位
# 3.1415926{:+.2}+3.14带符号保留小数点后两位
# -1{:+.2f}-1.00带符号保留小数点后两位
# 2.71828{0f}3不带小数
# 5{:0>2d}05数字补零(填充左边,宽度为2)
# 5{x<4d}5xxx数字补(填充右边,宽度为4)
# 10{x<4d}10x数字补(填充右边,宽度为4)
# 1000000{:}1,00,000以逗号分隔的数字格式
# 0.25{:2%}25.00%百分比格式
# 1000000002e}1.00e+09指数记法
# 13{:10d}13右对齐(默认,宽度为10)
# 13{<10d}13左对齐(宽度为10)
# 13{^10d}13中间对齐(宽度为10)
#  '{:b}' .format(11) 1011
#  '{:d}'.format(11) 11
#
# 11的进制'{:0}'.format(11)13
#  '{:x}'.format(11)b
#  '{:#x}' format(11)Oxb
#  '{#X}' .format(11)OXB
#
# ^,<,>分别是居中、左对齐、右对齐,后面带宽度,:号后面带填充的字符,只能是一个字
# 符,不指定则默认是用空格填充。
# +表示在正数前显示+,负数前显示- ,(空格)表示在正数前加空格
# b、d、O、x分别是二进制、十进制、八进制、十六进制。
# """

# 字典
# return 0:一般用在主函数结束时,按照程序开发的一般惯例,表示成功完成本函数。
# return -1::表示返回一个代数值,一般用在子函数结尾。按照程序开发的一般惯例,表示该函数失败;
# 以上两个是约定俗成,系统提供的函数绝大部分定义为int类型返回值的都是这样的。返回值是返回给系统用的,给系统看得。一般做调试的时候也会用的,当出现错误的时候可以根据返回值来确定问题出在哪一个函数上的。

print('========下面内容运行错误,还需要好好研究format和函数应用===========')
t={'year':'2013','month':'9','day': '30','hour' :'16','minute': '45','second':'2'}
print('{}{}{}'.format(t['year'],t['month'],t['day']),'{}{}{}'.format(t['hour'],t['minute'],t['second']))
s14=t.values()
s15=t.keys()
print(s14,s15)
# s16 ='{}{:>02}{>02}'.format(t['year'],t['month'],t['day'])
# s17='{}{:>02}{:>02}'.format(t['hour'],t['minute'],t['second'])
# print(s16,s17)
# print(str('-'.join(s14.split()),end=''))
# print(str(':'.join(s15.split())))
# """
#  :param 日期字典
#  :return:str 格式化后的日期
# """
# def data_to_str(d):
#     s17='{}{:>02}{:>02)'.format(t['year'],t['month'],t['day'])
#     s18='{}{:>02} {:>02}'.format(t['hour'],t['minute'],t['second'])
#     print(s17,s18)
#     print('-'.join(s17.split()),end='')
#     print(':'.join(s18.split()))
#     return 0
# t={'year':'2013','month':'9','day': '30','hour' :'16','minute': '45','second':'2'}
# print(data_to_str(d))

s20= '{0:10}={1:10}'.format('spam',1234567) #{0:10} 第一个数值0起10位,不足用空格填充
print('s20为:',s20)
s21 = '{0:>10}={1:<10}'.format('spam',1234567)
print('s21为:',s21)
s22='{0.platform:>10}={1[item]:<10}'.format(sys,dict(item='laptop'))
print(sys.platform,'s22为:',s22)

s23='{0:e},{1:3e},{2:g}'.format(3.14159,3.14159,3.14159) #g代表浮点型格式化
print(s23)

s24='{0:f},{1:2f},{2:06.2f},{2:07.2f}'.format(3.14159,3.14159,3.14159)#f 6位数值
print(s24)

print('========fomat格式化数值,支持二进制八进制十六进制===========')
s25='{0:2f},{0:.02f},{0:2f}'.format(1/3.0,1/3.0,1/3)
print(s25)
s26= '%.2f'%(1/3.0) #这个方式常用,与上面做比较
print(s26)
s27 ='%.*f'%(4,1/3.0) #注意这种写法  前面是位置 后面是值
print(s27)

s28 = '{0:.2f}'.format(1.2345)
s29 = format(1.2345,'.2f')
s30 = '%.2f'%1.2345
print(s28,s29,s30)

print('========这张看的懂,但是容易出错,format挺麻烦===========')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老来学python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值