python|格式化方法——format()
来源:互联网 发布:linux vim u撤销不了 编辑:程序博客网 时间:2024/06/16 18:18
format()方法的作用和“%”是一样的,都有格式化字符的作用,但是format()方法更加灵活。
1、使用参数确定位置
位置参数可确定任一参数,任一次数,使用列表时需要加上‘*’
>>> identy = ['John',20]>>> 'I am {} and {} years old'.format('John',20)#默认位置参数'I am John and 20 years old'>>> 'my name is {0} and {1} years old'.format('John',20)#使用位置参数'my name is John and 20 years old'>>> 'my name is {0} and {0}{1} years old'.format('John',20)#使用位置参数'my name is John and John20 years old'>>> 'my name is {} and {} years old'.format(*identy)#用列表时需要加‘*’'my name is John and 20 years old'>>>
2、通过关键字参数
通过关键字参数确定值,字典前需加**
>>> dic = {'name':'John','age':20}>>> 'my name is {name} and {age} years old'.format(**dic)'my name is John and 20 years old'>>> 'my name is {name} and {age} years old'.format(name='John',age = 20)
3、精度与类型
>>> '{0:.2f}'.format(1/3)'0.33'>>> '{0:b}'.format(10) #二进制'1010'>>> '{0:o}'.format(10) #八进制'12'>>> '{0:x}'.format(85) #16进制'55'>>> '{0:#x}'.format(85) #加#号可以显示进制'0x55'
4、填充与格式化
:[填充字符][对齐方式 <^>][宽度]
^、<、>分别是居中、左对齐、右对齐,最后指定宽度
’:‘号后带填充的字符只能是一个字符,默认是用空格填充
>>> '{0:*>15}'.format('我爱python') ##右对齐'*******我爱python'>>> '{0:*^15}'.format('我爱python') ##左对齐'***我爱python****'>>> '{0:*<15}'.format('我爱python') ##居中对齐'我爱python*******'
5、使用下标
>>> w =[(1,3),(4,6),(5,8)]>>> '{1[1]}'.format(*w) #其实就是输出w[1][1]的字符'6'
阅读全文
0 0
- python|格式化方法——format()
- Python字符串格式化--format()方法
- Python——format字符串格式化
- Python里的格式化字符串方法format
- python中format()方法格式化字符串
- %格式化和format格式化--python
- python format格式化字符串
- Python 格式化format
- python.format() 格式化字符串
- Python格式化字符串format
- python-格式化输出-format
- Python format 格式化函数
- python:格式化字符串,format
- Python string格式化format
- python学习——format方法总结
- Python中使用.format方法替代格式化操作符%
- python字符串格式化方法之%s和format函数
- python 格式化输出 format()
- pip 警告!The default format will switch to columns in the future
- storm入门简介、架构原理分析
- flask表单post传数据
- 关联容器<map>
- Python·Jupyter Notebook各种使用方法记录·持续更新
- python|格式化方法——format()
- 338. Counting Bits
- Git命令大集结
- 【ORACLE】Runstatus_pkg 性能比较工具脚本及使用
- Elasticsearch_基本操作
- BZOJ 1059 矩阵游戏 二分图匹配
- Swift项目引入react-native
- AndroidStdio集成FFmpeg
- 使用Maven构建web项目时的基本过程