引言
文章中的全部例子均在python2.7.6中测试通过
很多时候,python内建类型或者用户自定义的数据类型的表现形式跟我们预期的表现形式会不一致,假设我现在有一个自定义的类:
class People(object): def __init__(self,name,sex,age,hobby): self.name = name self.sex = sex self.age = age self.hobby = hobby
我们来实例化这个类如下:
p = People("an","man",27,("Reading","Game","BasketBall"))
python交互界面显示该实例:
>>> p <__main__.People object at 0x01FDD770>
从显示结果来看,我们只能知道该实例为People的实例,其余的信息一概不知,调试起来很不方便,再看看使用了格式化字符串的类定义:
class People(object): def __init__(self,name,sex,age,hobby): self.name = name self.sex = sex self.age = age self.hobby = hobby def __repr__(self): return "My name is %s,I am a %s,%d years old,like %s"%(self.name,self.sex,self.age,self.hobby)
备注:类的__repr__方法在此不做过多的介绍,你只需要知道实现了类的该特殊方法后,当需要显示该类的实例对象时并会调用该方法
再看看该类实例:
>>> p = People("an","man",27,("Reading","Game","BasketBall")) >>> p My name is an,I am a man,27 years old,like ('Reading', 'Game', 'BasketBall') >>>
较之前版本,我们可以清晰的看到该实例的信息。
编程活动中用到“字符串格式化”的地方举不胜举,下面我们就来具体说说python中的“字符串格式化”
python中的字符串格式化
字符串格式化符号
字符串格式化符号是基础,个人觉得只需要记住常用的,其余的到需要使用时再查阅参考书也不为迟(这可能也是我写博客的一个动机,记录下来等到需要的时候方便查看)
格式化字符 | 转换方式 |
---|---|
%c | 转换成字符(ASCII码值,或者长度为1的字符串) |
%r | 优先使用repr()函数进行字符串转换 |
%s | 优先使用str()函数进行字符串转换 |
%d、%i | 转换成有符号十进制数 |
%u | 转换成无符号十进制数 |
%o | 转换成无符号八进制数 |
%x、%X | 转换成无符号十六进制数(x/X代表转换后十六进制的大小写) |
%e、%E | 转换成科学计数 |
%f、%F | 转换成浮点数 |
%g、%G | %e和%f、%E和%F的简写 |
%% | % |
使用方法
- 元组方式
"xxx格式化符号1...格式化符号n"%(agr1,...,argn),字符串%需要格式化的元组
- 字典方式
"%(arg1)s...%(argn)s"%(agr1,...,argn),字符串%需要格式化的字典,字典的键必须在前面的格式化符号中间的括号中出现
使用案例
元组方式
>>> formatStrOne = "I am %s,%d(%o in octal an %x or %X in hexadecimal)years old,annual average wage:%.2f(%g in scientific notation)" >>> class Clerk(object): def __init__(self,name,age,averageWage): self.name = name self.age = age self.wage = averageWage >>> a = Clerk("a",26,3506.5832) >>> b = Clerk("b",28,4506.865) >>> c = Clerk("c",30,9000.6545) >>> all = [a,b,c] >>> for eachClerk in all: print formatStrOne%(eachClerk.name,eachClerk.age,eachClerk.age,eachClerk.age,eachClerk.age,eachClerk.wage,eachClerk.wage) I am a,26(32 in octal an 1a or 1A in hexadecimal)years old,annual average wage:3506.58(3506.58 in scientific notation) I am b,28(34 in octal an 1c or 1C in hexadecimal)years old,annual average wage:4506.86(4506.86 in scientific notation) I am c,30(36 in octal an 1e or 1E in hexadecimal)years old,annual average wage:9000.65(9000.65 in scientific notation) >>>
字典方式
>>> formatStrOne = "I am %(name)s,%(age)d(%(age)o in octal an %(age)x or %(age)X in hexadecimal)years old,annual average wage:%(wage).2f(%(wage)g in scientific notation)" >>> a = Clerk("a",26,3506.5832) >>> b = Clerk("b",28,4506.865) >>> c = Clerk("c",30,9000.6545) >>> all = [a,b,c] >>> for eachClerk in all: print formatStrOne%{"name":eachClerk.name,"age":eachClerk.age,"wage":eachClerk.wage,} I am a,26(32 in octal an 1a or 1A in hexadecimal)years old,annual average wage:3506.58(3506.58 in scientific notation) I am b,28(34 in octal an 1c or 1C in hexadecimal)years old,annual average wage:4506.86(4506.86 in scientific notation) I am c,30(36 in octal an 1e or 1E in hexadecimal)years old,annual average wage:9000.65(9000.65 in scientific notation) >>>
附表
符号 | 作用 |
---|---|
-(减号) | 左对齐 |
+(正号) | 在正数前面显示+ |
# | 在八进制数前面显示0,十六进制前面显示0x、0X |
0 | 显示数字前填充0而不是默认的空格 |
m.n | m是显示的最小总宽度,n是小数点后的位数 |
.n | n是小数点后的位数,不限制显示的最小总宽度 |
另外的方法
新式字符串模板Template的加入使得即将被废弃的string模块重新活了过来,Template对象有两个方法,substitute()和safe_substitute(),前者在缺少字典键值时抛出异常,后者则原封不动的输出格式字符串,使用如下:
>>> from string import Template >>> t = Template("I am ${name},${age} years old,annual average wage:${wage}") >>> data = {"name":"an","age":26} >>> t.substitute(**data) Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> t.substitute(**data) File "C:\Python27\lib\string.py", line 172, in substitute return self.pattern.sub(convert, self.template) File "C:\Python27\lib\string.py", line 162, in convert val = mapping[named] KeyError: 'wage' >>> t.safe_substitute(**data) 'I am an,26 years old,annual average wage:${wage}</span>' >>> data["wage"] = 3658.256 >>> t.substitute(**data) 'I am an,26 years old,annual average wage:3658.256' >>> t.safe_substitute(**data) 'I am an,26 years old,annual average wage:3658.256' >>>