python formatting function foramt

#By position
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') via keyword arguments

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

#Padding and alignment
print '{:>8}'.format('189')
# 189
print '{:0>8}'.format('189')
#00000189
print '{:a>8}'.format ('189')
#aaaaa189

#Precision and type f #Keep
two decimal places
print '{:.2f}'.format(321.33345)
#321.33

#Thousand separator used for amount
print '{:,}'.format(1234567890)
#1,234,567,890

#Other types are mainly hexadecimal, b, d, o, and x are binary, decimal, octal, and hexadecimal respectively.

print '{:b}'.format(18) #binary 10010
print '{:d}'.format(18) #decimal 18
print '{:o}'.format(18) #octal 22
print '{:x }'.format(18) #hexadecimal 12

 

This article is reprinted from https://www.cnblogs.com/gide/p/6955895.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325353823&siteId=291194637