Python:format函数用法整理

format优点
format是python2.6新增的一个格式化字符串的方法,相对于老版的%格式方法,它有很多优点。

1.不需要理会数据类型的问题,在%方法中%s只能替代字符串类型

2.单个参数可以多次输出,参数顺序可以不相同

3.填充方式十分灵活,对齐方式十分强大

4.官方推荐用的方式,%方式将会在后面的版本被淘汰

具体用法:

1.通过位置

#通过位置
print('{0},{1}'.format('chuhao',20))

print('{},{}'.format('chuhao',20))

print ('{1},{0},{1}'.format('chuhao',20))

#输出
chuhao,20

chuhao,20

20,chuhao,20

2.通过关键字参数

#通过关键字参数
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)))

#输出
chuhao,18

This guy is chuhao,is 18 old

3.通过映射 list

#通过映射 list
a_

你可能感兴趣的:(python,开发语言)