Python实现字符串格式化输出的方法详解


Posted in Python onSeptember 20, 2017

本文实例讲述了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程序设计有所帮助。

Python 相关文章推荐
Java Web开发过程中登陆模块的验证码的实现方式总结
May 25 Python
python验证码识别实例代码
Feb 03 Python
利用Python实现在同一网络中的本地文件共享方法
Jun 04 Python
python进行文件对比的方法
Dec 24 Python
Python学习笔记之Zip和Enumerate用法实例分析
Aug 14 Python
python读写Excel表格的实例代码(简单实用)
Dec 19 Python
Python Json数据文件操作原理解析
May 09 Python
Pytorch通过保存为ONNX模型转TensorRT5的实现
May 25 Python
python实现数学模型(插值、拟合和微分方程)
Nov 13 Python
python使用smtplib模块发送邮件
Dec 17 Python
matlab xlabel位置的设置方式
May 21 Python
python开发人人对战的五子棋小游戏
May 02 Python
Python+Selenium+PIL+Tesseract自动识别验证码进行一键登录
Sep 20 #Python
python select.select模块通信全过程解析
Sep 20 #Python
基于python的字节编译详解
Sep 20 #Python
MySQL适配器PyMySQL详解
Sep 20 #Python
Python字符串格式化的方法(两种)
Sep 19 #Python
python3 pillow生成简单验证码图片的示例
Sep 19 #Python
Python文件操作之合并文本文件内容示例代码
Sep 19 #Python
You might like
解析php类的注册与自动加载
2013/07/05 PHP
php判断页面是否是微信打开的示例(微信打开网页)
2014/04/25 PHP
php计算多个集合的笛卡尔积实例详解
2017/02/16 PHP
ExtJS 2.0实用简明教程 之ExtJS版的Hello
2009/04/29 Javascript
window.onload 加载完毕的问题及解决方案(下)
2009/07/09 Javascript
JavaScript中清空数组的三种方法分享
2011/04/07 Javascript
jQuery时间轴插件使用详解
2015/07/16 Javascript
浅谈JavaScript中的分支结构
2016/07/01 Javascript
three.js中3D视野的缩放实现代码
2017/11/16 Javascript
微信小程序实现漂亮的弹窗效果
2020/05/26 Javascript
JS实现自定义弹窗功能
2018/08/08 Javascript
通过javascript实现段落的收缩与展开
2019/06/26 Javascript
jquery实现垂直无限轮播的方法分析
2019/07/16 jQuery
react用Redux中央仓库实现一个todolist
2019/09/29 Javascript
微信小程序 行的删除和增加操作实现详解
2019/09/29 Javascript
[53:50]CHAOS vs Mineski 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/18 DOTA
用Python编写一个国际象棋AI程序
2014/11/28 Python
python制作最美应用的爬虫
2015/10/28 Python
解决python2.7 查询mysql时出现中文乱码
2016/10/09 Python
Python读取文件内容的三种常用方式及效率比较
2017/10/07 Python
Django框架序列化与反序列化操作详解
2019/11/01 Python
Python多线程模块Threading用法示例小结
2019/11/09 Python
Python中filter与lambda的结合使用详解
2019/12/24 Python
使用pyecharts1.7进行简单的可视化大全
2020/05/17 Python
EGO Shoes美国/加拿大:英国时髦鞋类品牌
2018/08/04 全球购物
创立科技Java面试题
2015/11/29 面试题
数控机械专业个人的自我评价
2014/01/02 职场文书
护理个人求职信范文
2014/01/08 职场文书
国培计划培训感言
2014/03/11 职场文书
合作经营协议书
2014/04/17 职场文书
公司会议策划方案
2014/05/17 职场文书
综治维稳工作汇报
2014/10/27 职场文书
小学见习报告
2014/10/31 职场文书
公司员工离职感言
2015/08/03 职场文书
《半截蜡烛》教学反思
2016/02/19 职场文书
Python基于百度AI实现抓取表情包
2021/06/27 Python