关于python的格式化函数 % 和 format

1:%
以前用的都是%,下面举个简单例子

#整数输出
print('%d' %17) #%d十进制
print('%x' %17) #%x 十六进制

#浮点数输出
print('%f' %2.468)  #%f 保留小数点后6位有效数字 
print('%.2f' %2.468) #%.nf 保留n位

#字符串输出
print('%s'  %'an tu tu or liu sha sha')

2:format()
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’。
format 函数可以接受不限个参数,位置可以不按顺序。
举个python简明教程中的例子,我加了一点点。

class Robot:

    #一个类变量,用来计数机器人的数量。
    population = 0      #population属于Robot类,因此它是一个类变量。所以通过 Robot.population引用population类变量。
    def __init__(self,name):   #name变量属于一个对象(通过使用self分配),因此它是一个对象变量。
        """初始化数据"""
        self.name = name
        print("(Initializing {})".format(self.name))
        #当有人被创建时,机器人将会增加人口数量
        Robot.population += 1   #还可以用self.__class__.population,因为每个对象都通过self.__class__属性来引用它的类。
        print("创建了{},".format(self.name),"此时机器人数量为{}..".format( Robot.population)) 

    def die(self):
        """我挂了"""
        print("{} is being destoryed!".format(self.name))
        Robot.population -= 1
        if Robot.population == 0:
            print("{} was the last one.".format(self.name))
        else:
            print("There are still {:d} robots working.".format(Robot.population))

    def say_hi(self):
        """来自机器人的问候,没问题你做得到."""
        print("Greetings, my masters call me {}.".format(self.name))

    @classmethod
    def how_many(cls):
        """打印出当前的人口数量。"""
        print("\nWe have {:d} robots.".format(cls.population))
    '''
    how_many是一个属于类的方法。使用装饰器将 how_many方法标记为类方法。
    可以将装饰器想象为一个包装器(Wrapper)函数的快捷方式,因此启用 @classmethod装饰器等价于调用how_many=classmethod(how_many)
    '''

droid1 = Robot("安兔兔")
droid1.say_hi()
#Robot.say_hi.__doc__
Robot.how_many()

droid2 = Robot("刘傻傻")
droid2.say_hi()
Robot.how_many()

print("\nRobots can do some work here.\n")

print("Robots have finshed their work. So let's destory them.")
droid1.die()
droid2.die()

Robot.how_many()


print("{1} {0} {1}".format("an tu tu","liu sha sha") )          

运行结果
这里写图片描述

关于更详细的format()可以看这个文章 ,比较详细。

http://www.runoob.com/python/att-string-format.html

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值