Python实现字符串格式化输出的方法详解
作者:tdoly 时间:2023-05-02 20:52:59
本文实例讲述了Python实现字符串格式化输出的方法。分享给大家供大家参考,具体如下:
python属于强类型的语言,如果像java一样操作字符串和数字的“+”时,会出现TypeError。而python的格式化方法有多种,比如使用占位符,使用format,或者是自定义模版等等。这里介绍了其中的几种方法
下面这个例子很好的说明了python属于强类型语言:
print "abc" + 123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
所以,需要进行转换输出。
常用占位符
符号 | 意思 |
%s | 字符串 |
%d / %i | 十进制整数 |
%u | 过时的十进制使用方法 |
%o | 八进制整数 |
%x / %X | 十六进制整数 |
%f / %F | 浮点数 |
%e / %E | 科学技术法 |
%% | 输出% |
使用方式一
直接使用占位符
print '%s+%d' % ('abc', 123) #abc+123
print '%o' % 10 #12 八进制
为%d指定长度,%05d,如果数字小于5位会在左边补0,大于指定长度时不受此影响
print '%s+%05d' % ('abc', 123) #abc+00123
print '%03x' % 10 #00a
print '%.3e' % 123456789 #1.235e+08 保留3位小数的科学技术法
使用方式二
使用字典
print 'Python is %(args)s, %(args)s, %(args)s beautiful' % {'args': 'very'} #Python is very, very, very beautiful
当拼接有许多重复元素时,使用这种方式比较好
使用方式三
使用format的方式。在2.6之后的版本支持。
print '{0}{1}{2}{3}'.format('a', 'b', 'c', 123) #abc123
print '{}, {}, {}'.format('a', 'b', 'c') #abc 2.7+ only
print '{2}, {1}, {0}'.format('a', 'b', 'c') #c, b, a
print '{2}, {1}, {0}'.format(*'abc') #c, b, a
print '{0}{1}{0}'.format('abra', 'cad') #abracadabra
通过参数名字格式化
print 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') #Coordinates: 37.24N, -115.81W
coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
print 'Coordinates: {latitude}, {longitude}'.format(**coord) #Coordinates: 37.24N, -115.81W
使用元组
coord = (3, 5)
print 'X: {0[0]}; Y: {0[1]}'.format(coord) #X: 3; Y: 5
进制
# format also supports binary numbers
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) #'int: 42; hex: 2a; oct: 52; bin: 101010'
3
# with 0x, 0o, or 0b as prefix:
"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42) #'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
为数字加点号
'{:,}'.format(1234567890) #'1,234,567,890'
百分比表示
'{:.2%}'.format(19.5 / 22) # '88.64%'
时间格式化
import datetime
today = datetime.datetime.today()
'{:%Y-%m-%d %H:%M:%S}'.format(d) #'2013-09-01 21:10:22'
'{:%Y-%m-%d}'.format(today) #'2013-09-01'
另外也可以使用strftime来格式化时间
使用方式四
自定义模版
from string import Template
s = Template('$sargs plus $aargs')
s.substitute(sargs = 'abc', aargs = 123) #'abc plus 123'
这里有substitue和safe_substitute两种属性
d = dict(sargs = 'abc')
# s.substitute(d)
# it's a KeyError
s.safe_substitute(d) #'abc plus $aargs'
如果不使用safe_substitute,参数不全时会出现KeyError异常。
希望本文所述对大家Python程序设计有所帮助。
来源:http://blog.tdoly.com/coding/python-string-format/
标签:Python,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python3 tkinter实现点击一个按钮跳出另一个窗口的方法
2023-10-27 01:19:11
![](https://img.aspxhome.com/file/2023/2/102342_0s.jpg)
python使用Plotly绘图工具绘制散点图、线形图
2022-06-24 08:11:50
![](https://img.aspxhome.com/file/2023/7/78607_0s.png)
各种JavaScript开发工具比较
2007-10-23 13:29:00
![](/images/sg_trans.gif)
Python实现灰色关联分析与结果可视化的详细代码
2023-08-03 15:01:56
![](https://img.aspxhome.com/file/2023/3/61703_0s.png)
思考关于搜索框的设计
2008-12-09 18:17:00
![](https://img.aspxhome.com/file/UploadPic/200812/9/techcrunch2-67.jpg)
关于Kotlin中SAM转换的那些事
2022-02-09 15:14:38
大家都对vertical-align的各说各话
2008-06-19 12:11:00
![](https://img.aspxhome.com/file/UploadPic/20086/19/2008619121517533s.gif)
Pytorch转tflite方式
2023-08-10 03:47:29
Flask数据库迁移简单介绍
2024-01-20 09:00:57
python中显存回收问题解决方法
2022-06-28 03:06:29
jupyter notebook 恢复误删单元格或者历史代码的实现
2022-03-03 16:13:45
![](https://img.aspxhome.com/file/2023/2/87562_0s.jpg)
asp连接各种数据库代码
2008-03-11 11:16:00
![](https://img.aspxhome.com/file/UploadPic/20083/11/2008311115714589s.jpg)
JavaScript数据结构中串的表示与应用实例
2023-08-26 10:38:38
MySql 快速插入千万级大数据的方法示例
2024-01-15 16:43:44
PHP入门速成(3)
2023-11-20 18:48:03
利用Python实现Excel的文件间的数据匹配功能
2023-12-04 19:53:42
![](https://img.aspxhome.com/file/2023/5/109845_0s.png)
大家一起来折磨浏览器吧!(好玩的东东)
2010-02-07 12:40:00
JavaScript中访问节点对象的方法有哪些如何使用
2024-06-18 10:50:36
python从入门到实践之组合数据类型
2021-09-02 17:53:54
Python如何读取PDF文档(或TXT)
2021-10-01 06:24:36
![](https://img.aspxhome.com/file/2023/4/100744_0s.png)