Python格式化字符串

来源:互联网 发布:discuz数据调用 编辑:程序博客网 时间:2024/05/16 07:25

在Python中可以使用string模块中的字符串模板(Template)对象进行字符串的格式化

>>> from string import Template

>>> s = Template('There are ${howmany} ${lang} Quotation Symbols')
>>>
>>> print s.substitute(lang='Python', howmany=3)
There are 3 Python Quotation Symbols
>>>
>>> print s.substitute(lang='Python')#出错,错误信息已删除
>>>
>>> print s.safe_substitute(lang='Python')

There are ${howmany} Python Quotation Symbols


以下转载自:http://www.cnblogs.com/wilber2013/p/4641616.html

Python2.6开始,新增了一种格式化字符串的函数str.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类型的内建函数:

# 小写 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)