python中强大的format函数实例详解

yipeiwu_com6年前Python基础

python中format函数用于字符串的格式化

自python2.6开始,新增了一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串。

语法

它通过{}和:来代替%。

请看下面的示例,基本上总结了format函数在python的中所有用法

#通过位置
print '{0},{1}'.format('chuhao',20)
print '{},{}'.format('chuhao',20)
print '{1},{0},{1}'.format('chuhao',20)
#通过关键字参数
print '{name},{age}'.format(age=18,name='chuhao')
class Person:
  def __init__(self,name,age):
    self.name = name
    self.age = age
  def __str__(self):
    return 'This guy is {self.name},is {self.age} old'.format(self=self)
print str(Person('chuhao',18))
#通过映射 list
a_list = ['chuhao',20,'china']
print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
#my name is chuhao,from china,age is 20
#通过映射 dict
b_dict = {'name':'chuhao','age':20,'province':'shanxi'}
print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
#my name is chuhao, age is 20,from shanxi
#填充与对齐
print '{:>8}'.format('189')
#   189
print '{:0>8}'.format('189')
#00000189
print '{:a>8}'.format('189')
#aaaaa189
#精度与类型f
#保留两位小数
print '{:.2f}'.format(321.33345)
#321.33
#用来做金额的千位分隔符
print '{:,}'.format(1234567890)
#1,234,567,890
#其他类型 主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。
print '{:b}'.format(18) #二进制 10010
print '{:d}'.format(18) #十进制 18
print '{:o}'.format(18) #八进制 22
print '{:x}'.format(18) #十六进制12

总结

以上所述是小编给大家介绍的python中强大的format函数实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python 对txt中每行内容进行批量替换的方法

python 对txt中每行内容进行批量替换的方法

如下所示: f = open('./val.txt') lines = f.readlines() #整行读取 f.close() for line in lines: rs =...

python matplotlib画图库学习绘制常用的图

python matplotlib画图库学习绘制常用的图

本文实例为大家分享了python matplotlib绘制常用图的具体代码,供大家参考,具体内容如下 github地址 导入相关类 import numpy as np import...

python实现简单加密解密机制

本文使用python实现一个简单的加密解密机制。 描述:结合26个字母、以一个单词作为秘钥,使用python实现简单的加密解密机制 秘钥:大写的英文字符串 明文:包含空格、大小写字母、数...

深入解析Python中的descriptor描述器的作用及用法

一般来说,一个描述器是一个有“绑定行为”的对象属性(object attribute),它的访问控制被描述器协议方法重写。这些方法是 __get__(), __set__(), 和 __...

在django中实现页面倒数几秒后自动跳转的例子

实现倒计时跳转要和html中的js结合起来, 例如:实现一个页面简单的注册,然后注册成功后倒计时自动跳转到登录页面。 # 注册页面 def register(request):...