博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python字符串格式化输出
阅读量:7063 次
发布时间:2019-06-28

本文共 3065 字,大约阅读时间需要 10 分钟。

python中有两种格式化输出字符串的方式:格式化表达式、format()方法。当然,还有一个简化操作的内置format()函数。

它们绝大部分功能都是重复的,熟悉printf的可以考虑使用格式化表达式,否则使用format()更友好些,因为它像处理函数参数一样,但format()有时候可能写的要更复杂。

格式化表达式

格式化表达式类似于printf的风格,在字符串中使用%作为占位符。本文只是介绍python中的一些特性,如有需要请自行搜索printf用法。

>>> who1 = "long">>> who2 = "shuai">>> "hello %s world" % "your"'hello your world'>>> "hello %s world" % who1'hello long world'>>> "hello %s world" % (who1)'hello long world'>>> "hello %s %s world" % (who1, who2)'hello long shuai world'

字符串和替换目标之间也使用%分隔,且替换部分可以有多个(使用括号包围),可以使用变量。

替换目标还可以使用字典,这时在字符串中的%占位符可以以key的方式来引用:

>>> "%(name1)s with %(name2)s" % {"name1":"longshuai", "name2":"xiaofang"}'longshuai with xiaofang'

用字典的形式,可以让表达式格式化更模板化。例如:

>>> reply = """... hello %(name)s!... Your age is %(age)d""">>>>>> values = {'name':"longshuai",'age':23}>>> print(reply % values)hello longshuai!Your age is 23

字符串格式化方法:format()

使用format()来格式化字符串时,使用在字符串中使用{}作为占位符,占位符的内容将引用format()中的参数进行替换。可以是位置参数、命名参数或者兼而有之。

看示例就明白了。

# 位置参数>>> template = '{0}, {1} and {2}'>>> template.format('long','shuai','gao')'long, shuai and gao'# 命名参数>>> template = '{name1}, {name2} and {name3}'>>> template.format(name1='long', name2='shuai', name3='gao')'long, shuai and gao'# 混合位置参数、命名参数>>> template = '{name1}, {0} and {name3}'>>> template.format("shuai", name1='long', name3='gao')'long, shuai and gao'

需要注意,format()函数中,位置参数必须放在所有的命名参数之前。例如,下面的会报错:

template.format(name1='long', "shuai", name3='gao')

因为字符串中的占位符是直接引用format中的参数属性的,在占位符处可以进行索引取值、方法调用等操作。例如:

>>> import sys>>> 'My {1[name]} OS is {0.platform}'.format(sys,{"name":"laptop"})'My laptop OS is win32'>>> 'My {config[name]} OS is {sys.platform}'.format(sys=sys,config={'name':'loptop'})'My loptop OS is win32'

但是,在占位符使用索引或切片时,不能使用负数,但可以将负数索引或负数切片放在format的参数中。

>>> s = "hello">>> 'first={0[0]}, last={0[4]}'.format(s)'first=h, last=o'# 下面是错的>>> 'first={0[0]}, last={0[-1]}'.format(s)# 下面是正确的>>> 'first={0[0]}, last={1}'.format(s, s[-1])'first=h, last=o'

format()作为函数,它也能进行参数解包,然后提供给占位符。

>>> s=['a','b','c']>>> '{0}, {1} and {2}'.format(*s)'a, b and c'

在占位符后面加上数值可以表示占用字符宽度。

>>> '{0:10} = {1:10}'.format('abc','def')'abc        = def       '>>> '{0:10} = {1:10}'.format('abc',123)'abc        =        123'>>> '{0:10} = {1:10}'.format('abc',123.456)'abc        =    123.456'

使用>表示右对齐,<表示左对齐,^表示居中对齐,并且可以使用0来填充空格。

>>> '{0:>10} = {1:>10}'.format('abc','def')'       abc =        def'>>> '{0:>10} = {1:<10}'.format('abc','def')'       abc = def       '>>> '{0:^10} = {1:^10}'.format('abc','def')'   abc     =    def    '>>> '{0:10} , {1:<06}'.format('abc','def')'abc        , def000'>>> '{0:10} , {1:>06}'.format('abc','def')'abc        , 000def'>>> '{0:10} , {1:^06}'.format('abc','def')'abc        , 0def00'

可以指定e、f、g类型的浮点数,默认采用g浮点数格式化。例如:

>>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)'3.141590, 3.14, 003.14'

:.2f表示保留两位小数,:06.2f表示最大长度位6字符,左边使用0填充而不是字符串,保留2位小数。

甚至,可以从format()中指定小数位数。

>>> '{0:.{1}f}'.format(1/3, 4)'0.3333'

内置函数format()

除了字符串方法format(),还提供了一个快速格式化单个字符串目标的内置函数format()。

用法示例:

>>> '{0:.2f}'.format(1.2345)'1.23'>>> format(1.2345, '.2f')'1.23'>>> '%.2f' % 1.2345'1.23'

转载地址:http://rtnll.baihongyu.com/

你可能感兴趣的文章
揭秘 DockerCon 重量级演讲嘉宾(六)
查看>>
性能优化技巧 - 集群维表
查看>>
python 静态文件以及一个项目框架
查看>>
组复制官方翻译七、Requirements and Limitations
查看>>
2019年4月上旬值得一读的10本技术书籍(Python、大数据、深度学习等)!
查看>>
微信钱包入口开发笔记
查看>>
[error] 17755#0: *58522 readv() failed (104: Connection reset by peer) while reading upstream
查看>>
如何从CRM中获益?看专家怎么说!
查看>>
捷信达会员管理系统SQL语句相关
查看>>
WPF DataGrid 每行ComboBox 内容不同的设置方法
查看>>
Confluence 6 管理和恢复空间管理权限
查看>>
实时计算Flink——独享模式——Batch功能介绍
查看>>
Robot Framework之使用Cookie获取验证码登录账户
查看>>
HBase生产环境配置与使用优化不完全指南
查看>>
mysql创建数据表时如何判断是否已经存在?
查看>>
RocketMQ 基本概念
查看>>
VUE多项目间跳转保存用户解决方法
查看>>
HashMap 详解四
查看>>
GCP为Kubernetes引擎提供支持原生容器的负载均衡器
查看>>
住宅格局解剖图鉴
查看>>