#通过位置
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 was {self.name},is {self.age} old '. Format (self=self)
Print str (person (' Chuhao ', 18))
#通过映射 List
A_list = [' Chuhao ', ' China ']
print ' My name ' {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 ': ' Province ': ' Shanxi '}
print ' My name ' {name}, age ' {age},from {province} '. Format (**b_dict)
#my name is Chuhao, 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
#其他类型 is mainly into the system, B, D, O, X is binary, decimal, octal, hexadecimal.
print ' {: b} '. Format #二进制 10010
print ' {:d} '. Format #十进制 18
print ' {: o} '. Format #八进制 22
print ' {: x} '. Format #十六进制12
This article was transferred from https://www.cnblogs.com/gide/p/6955895.html
Python Format function Foramt