Python培训
400-996-5531
普通使用
# 通过位置 info1 = '{}, {}'.format('Gage', 25) # Gage,25 info2 = '{1}, {1}'.format('Gage', 25) # 25,25 # 通过下标(列表) p = ('Gage', 25) print('{0[0]}'.format(p)) # Gage print('{0[0]}, {0[1]}'.format(p)) # Gage,25 # 通过关键字参数 print('{name}, {age}'.format(name="Gage", age=25)) # Gage 25 print('{[name]}'.format(dict(name="I'm Gage"))) # I'm Gage # 元组和字典info = ('Ggae', 25) site = {'company': 'xitucheng', 'home': 'zhuxinzhuang'} print("I'm {0}, {1} years old, working in {company}.".format(*info, **site)) # I'm Ggae, 25 years old, working in xitucheng.
高级使用
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return "This boy is {self.name}, {self.age} years old.".format(self=self) p = Person('Gage', 25)print(p)
进阶使用
# 填充和对齐 1、^、<、>分别是居中、左对齐、右对齐,后面带宽度 2、:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充 print('{:t>8}'.format(189)) # ttttt189 print('{:t<8}'.format(189)) # 189ttttt print('{:t^8}'.format(189)) # tt189ttt # 进制转换 1、b、d、o、x分别是二进制、十进制、八进制、十六进制 print('{:b}'.format(10)) # 1010 print('{:d}'.format(10)) # 10 print('{:o}'.format(10)) # 12 print('{:x}'.format(10)) # a # 精度转换 print('{:.2f}'.format(3.1415926)) # 3.14 # 科学计数法 print('{:8e}'.format(189)) # 1.890000e+02 # 金额分割 print('{:,d}'.format(1234567890)) # 1,234,567,890 # 百分比print('{:%}'.format(0.314)) # 31.400000% # 日期格式自定义 from datetime import datetime print("Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())) # Today is: Tue Jun 11 17:21:15 2019免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。
填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!
Copyright © 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有
Tedu.cn All Rights Reserved