python format
Python format
2023-09-27 14:25:21 时间
python自2.6后,新增了一种格式化字符串函数str.format(),威力十足,可以替换掉原来的%
注:以下操作版本是python2.7
映射示例
语法
通过{} 和 : 替换 %
通过位置
>>> '{0} is {1}'.format('jihite', '4 years old') 'jihite is 4 years old' >>> '{0} is {1} {0}'.format('jihite', '4 years old') 'jihite is 4 years old jihite'
通过format函数可以接受不限参数个数、不限顺序
通过关键字
>>> '{name}:{age}'.format(age=4,name='jihite') 'jihite:4' >>> '{name}:{age}'.format(age=4,name='jihite',locate='Beijing') 'jihite:4'
format括号内用=给变量赋值
通过对象属性
>>> class Person: ... def __init__(self, name, age): ... self.name,self.age = name, age ... def __func__(self): ... return "This guy is {self.name}, is {self.age} old".format(self=self) ... >>> s =Person('jihite', 4) >>> s.__func__() 'This guy is jihite, is 4 old'
通过下标
>>> '{0[0]} is {0[1]} years old!'.format(['jihite', 4]) 'jihite is 4 years old!' >>> '{0} is {1} years old!'.format('jihite', 4) 'jihite is 4 years old!'
其实就是通过位置
格式限定符
通过{} : 符号
填充和对齐
^<>分别表示居中、左对齐、右对齐,后面带宽度
>>> '{:>10}'.format('jihite') ' jihite' >>> '{:<10}'.format('jihite') 'jihite ' >>> '{:^10}'.format('jihite') ' jihite '
精度和类型f
精度常和f一起使用
>>> '{:.2f}'.format(3.1415) '3.14' >>> '{:.4f}'.format(3.1) '3.1000'
进制转化
>>> '{:b}'.format(10) '1010' >>> '{:o}'.format(10) '12' >>> '{:d}'.format(10) '10' >>> '{:x}'.format(10) 'a'
其中b o d x分别表示二、八、十、十六进制
千位分隔符
>>> '{:,}'.format(1000000) '1,000,000'
>>> '{:,}'.format(100000.23433)
'100,000.23433'
>>> '{:,}'.format('abcedef') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Cannot specify ',' with 's'.
这种情况只针对数字
相关文章
- Python 日期 的 加减 等 操作
- python切片越界不会报错,会自动锁定在边界值
- 【华为OD机试真题 python】报文解压缩【2022 Q4 | 200分】
- 如何高效自学python?
- python format格式化函数详解
- Python: ISO 8601 format datime
- Python: format __format__
- Python--爬虫--re(正则表达式)入门
- 《Python机器学习实践指南》——导读
- 图像处理:随机添加椒盐噪声和高斯噪声Python
- Python学习之DateTime、TimeDelta、Strftime(Format)及其示例
- python学习之利用format()或zfill()函数对数据进行编号排序的应用
- python ndarray相关操作:切分
- python 脚本如何在后代运行并记录标准输出
- Python 自定义元类的两种写法
- 《Python语言程序设计》——3.5 对象和方法简介
- linux系统 python虚拟环境安装TensorFlow
- 【Python分布式服务框架】Docker部署Postgresql主从复制模式
- 基于Selenium2与Python自动化测试环境搭建
- python 第三方库之openpyxl excel单元格中的公式提取
- Python .format()的详细使用(英文版)
- Python遍历字典
- 看我如何基于Python&Facepp打造智能监控系统