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

yipeiwu_com5年前Python基础

本文实例讲述了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字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》。

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python入门教程4. 元组基本操作 原创

前面简单介绍了Python列表基本操作,这里再来简单讲述一下Python元组相关操作 >>> dir(tuple) #查看元组的属性和方法 ['__add__',...

python脚本调用iftop 统计业务应用流量的思路详解

因公司服务器上部署应用较多,在有大并发访问、业务逻辑有问题的情况下反复互相调用或者有异常流量访问的时候,需要对业务应用进行故障定位,所以利用python调用iftop命令来获取应用进程流...

python处理大日志文件

本文实例为大家分享了python处理大日志文件的具体代码,供大家参考,具体内容如下 # coding=utf-8 import sys import time class Ta...

python函数式编程学习之yield表达式形式详解

前言 yield的英文单词意思是生产,刚接触Python的时候感到非常困惑,一直没弄明白yield的用法。最近又重新学习了下,所以整理了下面这篇文章,供自己和大家学习参考,下面话不多说了...

如何不用安装python就能在.NET里调用Python库

如何不用安装python就能在.NET里调用Python库

前言 Pythonnet这个屌爆的项目的出现,使得我们可以用一种新的方式,让C#可以和Python之间进行互操作。但是它的设置和部署可能有点问题,真的是这样吗? 本文我会介绍Python...