说明 :format 通过 {} 来替换 % 进行格式化,{} 叫做占位符 ,% 形式的格式化,是从C语言继承过来的,printf style 字符串格式化
语法:1, s = 'i love {}' s.format('python') 会打印 'i love python'
2, s = 'i love {} i am {}' s.format('python',18) 会打印 'i love python i am 18'
3, s = 'i love {1},i am {0}' s.format(18,'python') 会打印 'i love python i am 18' 通过位置参数实现
4, s = 'my name is {0},i love {lang},i am {age}'.format('andy',lang='python',age =18) 位置参数和关键字参数混合,同时支持
print s 会打印出 ‘my name is andy,i love python , i am 18’
5,'{0}{0}'.format('haha') 会打印'hahahaha' 参数可以通过指定位置多次进行调用
6, '{0}{1}'.format('haha','heihei') 会打印'hahaheihei'
实例:
通过函数的方式进行调用format
#!/usr/bin/env python
#coding:utf8
#类函数
class Employee: #创建一个类
empcount = 0
def __init__(self,name,salary,age): #初始化
self.name = name
self.salary = salary
self.age = age
Employee.empcount += 1
def displayCount(self): #对员工进行计数
print"员工总数为 {}".format(self.empcount)
def displayEmployee(self): #展示员工的基本资料
print "The employee is {},".format(self.name),"salary is {},".format(self.salary),"age is {}".format(self.age)
#创建类的实例
emp1 = Employee("andy",20000,18)
emp2 = Employee("liush",10000,28)
emp1.displayCount()
emp1.displayEmployee()