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)
阅读全文
0 0
- Python字符串格式化符号
- PYTHON 字符串格式化
- 字符串格式化(python)
- Python:字符串格式化
- python字符串格式化
- Python字符串格式化
- Python字符串格式化问题
- python字符串的格式化
- python 格式化字符串
- Python字符串格式化
- python 格式化时间字符串
- python 格式化字符串
- python 字符串格式化
- Python中的格式化字符串
- Python字符串格式化
- python format格式化字符串
- Python字符串格式化
- Python字符串格式化
- 关于卡尔曼滤波和卡尔曼平滑关系的理解
- 树莓派3+openwrt+nodogsplash实现portal认证
- 原生Js完美运动框架(缓冲运动和弹性运动)
- 白名单和黑名单概念
- 基于Java Bouncy Castle的PGP加密解密示例
- Python格式化字符串
- HDU
- 二叉树的深度
- SSM 整合发生异常:Error creating bean with name 'itemsController': Injection of resource dependencies fail
- 如何使用C#自带的GDI+双缓冲类BufferedGraphics实现双缓冲功能
- 用Java实现将一个字符串中的空格换成%20
- 【PAT】【Advanced Level】1103. Integer Factorization (30)
- 解决方案--爬虫拿到的HTML和浏览器中的源码不相同
- 测试的简单基本流程