About formatting ---- format string and%

There are two general methods formatted string

1,% (d integer, s character, f float) 2, format has extremely broad and useful few restrictions

Note: The first delivery will be reported to the array TypeError, it is necessary to pass an array

a = (1, 2, 3)
# b = 'I have %s' % (a) b = 'I have %s' % (a,) print(b) 

pass parameters format

1, location

a = '{0}:{1}'.format('abc', 123)
print(a) 

2, Keyword

a = '{name},{age}'.format(name='Mike', age=28)
print(a) 

3, object properties

class Person:
    def __init__(self, name, age): self.name, self.age = name, age def __str__(self): return 'This guy is {self.name},is {self.age} old'.format(self=self) a = str(Person('Lucy', 18)) print(a) 

4, the index for the list, such as an ordered set of arrays

p = ['kzc', 18]
a = '{0[0]},{0[1]}'.format(p) print(a) 

format defined format

1, is aligned below the filling> Table right-aligned <Left ^ character before filling centered object notation

a = '{:>8}'.format('189')
print(a) b = '{:0>8}'.format('189') print(b) c = '{:a>8}'.format('189') print(c) 

2, and the accuracy of the type often used with f

a = '{:.2f}'.format(33.333333)
print(a) 

3, binary digital conversion

a = 17
print('{:b}'.format(a), '二进制') print('{:x}'.format(a), '十六进制') print('{:d}'.format(a), '十进制') print('{:o}'.format(a), '八进制') 

4, thousands separator

a = 1234567890

print('{:,}'.format(a))

Guess you like

Origin www.cnblogs.com/Zhao01/p/11840859.html