Python格式化字符串
在编写程序的过程中,经常需要进行格式化输出,每次用每次查。干脆就在这里整理一下,以便索引。
格式化操作符(%)
"%" 是 Python 风格的字符串格式化操作符,非常类似 C 语言里的 printf() 函数的字符串格式化(C 语言中也是使用 %)。
下面整理了一下 Python 中字符串格式化符合:
格式化符号 |
说明 |
%c |
转换成字符(ASCII 码值,或者长度为一的字符串) |
%r |
优先用 repr() 函数进行字符串转换 |
%s |
优先用 str() 函数进行字符串转换 |
%d / %i |
转成有符号十进制数 |
%u |
转成无符号十进制数 |
%o |
转成无符号八进制数 |
%x / %X |
转成无符号十六进制数(x / X 代表转换后的十六进制字符的大小写) |
%e / %E |
转成科学计数法(e / E 控制输出 e / E) |
%f / %F |
转成浮点数(小数部分自然截断) |
%g / %G |
%e 和 %f / %E 和 %F 的简写 |
%% |
输出 % (格式化字符串里面包括百分号,那么必须使用 %%) |
这里列出的格式化符合都比较简单,唯一想要强调一下的就是 "%s" 和 "%r" 的差别。
看个简单的代码:
string = "Hello\tWill\n"print "%s" %string
print "%r" %string
代码的输出为:
其实,这里的差异是 str()和 repr() 两个内建函数之间的差异:
- str() 得到的字符串是面向用户的,具有较好的可读性
-
repr() 得到的字符串是面向机器的
- 通常(不是所有)repr()得到的效果是:obj == eval(repr(obj))
格式化操作符辅助符
通过 "%" 可以进行字符串格式化,但是 "%" 经常会结合下面的辅助符一起使用。
辅助符号 |
说明 |
* |
定义宽度或者小数点精度 |
- |
用做左对齐 |
+ |
在正数前面显示加号 (+) |
# |
在八进制数前面显示零 (0),在十六进制前面显示 "0x" 或者 "0X"(取决于用的是 "x" 还是 "X") |
0 |
显示的数字前面填充 "0" 而不是默认的空格 |
(var) |
映射变量(通常用来处理字段类型的参数) |
m.n |
m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |
看一些简单的 例子:
num = 100print "%d to hex is %x" %(num, num)
print "%d to hex is %X" %(num, num)
print "%d to hex is %#x" %(num, num)
print "%d to hex is %#X" %(num, num)# 浮点数
f = 3.1415926
print "value of f is: %.4f" %f# 指定宽度和对齐
students = [{"name":"Wilber", "age":27}, {"name":"Will", "age":28}, {"name":"June", "age":27}]
print "name: %10s, age: %10d" %(students[0][<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">"</span>], students[0][<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">age</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">])
print "name: %-10s, age: %-10d" %(students[1][<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">"</span>], students[1][<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">age</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">])
print "name: %s, age: %0d" %(10, students[2][<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">name</span><span style="color: rgba(128, 0, 0, 1)">"</span>], 10, students[2][<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">age</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">])# dict 参数
for student in students:
print "%(name)s is %(age)d years old" %student
代码输出为:
对于 Python 的格式化操作符,不仅可以接受 tuple 类型的参数,也可以支持 dict,象上面代码的最后一部分,那么格式化字符串中就可以直接使用 "%(key)s"(这里的 s 根据具体类型改变)的方式表示 dict 中对应的 value 了。
字符串模板
其实,在 Python 中进行字符串的格式化,除了格式化操作符,还可以使用 string 模块中的字符串模板(Template)对象。下面就主要看看 Template 对象的 substitute() 方法:
from string import Templates = Template("Hi, $name! $name is learning $language")
print s.substitute(name="Wilber", language="Python")d = {"name": "Will", "language": "C#"}
print s.substitute(d)# 用 $$ 表示 $ 符号
s = Template("This book ($bname) is 17$$")
print s.substitute(bname="TCP/IP")
代码结果为:
字符串内建函数 format()
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),通过这个函数同样可以对字符串进行格式化处理。在 format() 函数中,使用“{}”符号来当作格式化操作符。
下面直接通过一些简单的例子演示 format() 函数的基本使用:
# 位置参数 print "{0} is {1} years old".format("Wilber", 28) print "{} is {} years old".format("Wilber", 28) print "Hi, {0}! {0} is {1} years old".format("Wilber", 28)# 关键字参数
print "{name} is {age} years old".format(name = "Wilber", age = 28)# 下标参数
li = ["Wilber", 28]
print "{0[0]} is {0[1]} years old".format(li)# 填充与对齐
# ^、<、> 分别是居中、左对齐、右对齐,后面带宽度
# : 号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
print '{:>8}'.format('3.14')
print '{:<8}'.format('3.14')
print '{:^8}'.format('3.14')
print '{:0>8}'.format('3.14')
print '{:a>8}'.format('3.14')# 浮点数精度
print '{:.4f}'.format(3.1415926)
print '{:0>10.4f}'.format(3.1415926)# 进制
# b、d、o、x 分别是二进制、十进制、八进制、十六进制
print '{:b}'.format(11)
print '{:d}'.format(11)
print '{:o}'.format(11)
print '{:x}'.format(11)
print '{:#x}'.format(11)
print '{:#X}'.format(11)# 千位分隔符
print '{:,}'.format(15700000000)
str 的内建函数
在最开始的时候,Python 有一个专门的 string 模块,要使用 string 的方法要先 import 这个模块。从 Python2.0 开始, 为了方便使用,str 类型添加了很多内建函数,这些函数可以实现跟 string 模块中函数相同的功能,也就是说,只要 S 是一个字符串对象就可以直接使用内建函数,而不用 import。
对于字符串的格式化处理,也可以考虑使用 str 的其他内建函数:
>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get slice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mo d__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook __', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index ', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', ' rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', ' strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
下面整理出来了一些常用的 str 类型的内建函数:
# 小写 S.lower() # 大写 S.upper() #大小写互换 S.swapcase() # 首字母大写 S.capitalize()# 输出 width 个字符,S 左对齐,不足部分用 fillchar 填充,默认的为空格。
S.ljust(width,[fillchar])
# 右对齐
S.rjust(width,[fillchar])
# 中间对齐
S.center(width, [fillchar])# 返回 S 中出现 substr 的第一个字母的标号,如果 S 中没有 substr 则返回 -1。start 和 end 作用就相当于在 S[start:end] 中搜索
S.find(substr, [start, [end]])
# 返回 S 中最后出现的 substr 的第一个字母的标号,如果 S 中没有 substr 则返回 -1,也就是说从右边算起的第一次出现的 substr 的首字母标号
S.rfind(substr, [start, [end]])
# 计算 substr 在 S 中出现的次数
S.count(substr, [start, [end]])
#把 S 中的 oldstar 替换为 newstr,count 为替换次数
S.replace(oldstr, newstr, [count])# 把 S 中前后 chars 中有的字符全部去掉,可以理解为把 S 前后 chars 替换为 None
S.strip([chars])
S.lstrip([chars])
S.rstrip([chars])# 以 sep 为分隔符,把 S 分成一个 list。maxsplit 表示分割的次数。默认的分割符为空白字符
S.split([sep, [maxsplit]])
# 把 seq 代表的字符串序列,用 S 连接起来
S.join(seq)
总结
本文整理了一些格式化字符,以及一些辅助指令,结合格式化操作符(%),就可以生成特定格式的字符串了。也可以使用字符串模板来进行字符串格式化。