Python[十一]:Format

Format >>>for x in range(1,11): print(repr(x).rjust(2),repr(x*x).rjust(3),end=' ') print(repr(x*x*x).rjust(4)) 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 >>> for x in range(1,11): print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x)) 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 >>> x=1212121. >>> x 1212121.0 >>> x.ljust(2)[:2] Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> x.ljust(2)[:2] AttributeError: 'float' object has no attribute 'ljust' >>> repr(x).ljust(2)[:2] '12' >>> '12'.zfill(5) '00012' >>> '-3.14'.zfill(7) '-003.14' >>> print('We are the {0} who say "{1}!"'.format('knights','Ni')) We are the knights who say "Ni!" >>> print('{0} and {1}'.format('spam','eggs')) spam and eggs >>> print('{1} and {0}'.format('spam','eggs')) eggs and spam >>> print('This is {index} name: {name}'.fomat(index=56,name='ICT')) Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> print('This is {index} name: {name}'.fomat(index=56,name='ICT')) AttributeError: 'str' object has no attribute 'fomat' >>> print('This is {index} name: {name}'.format(index=56,name='ICT')) This is 56 name: ICT >>> import math >>> print('The value of PI is approximately {0:.3f}'.format(math.pi)) The value of PI is approximately 3.142 >>> The value of PI is approximately 3.142 SyntaxError: invalid syntax (<pyshell#20>, line 1) >>> table={'Sjored':4127,'Jack':4098,'Dcab':7678} >>> for name,phone in table.items(): print('{0:10} ==> {1:10d}'.format(name,phone)) Dcab ==> 7678 Sjored ==> 4127 Jack ==> 4098 >>> table {'Dcab': 7678, 'Sjored': 4127, 'Jack': 4098} >>> print('Jack:{0[Jack]:d};Sjored:{0[Sjored]:d};') Jack:{0[Jack]:d};Sjored:{0[Sjored]:d}; >>> print('Jack:{0[Jack]:d};Sjored:{0[Sjored]:d};Dcab:{0[Dcab]:d}'.format(table)) Jack:4098;Sjored:4127;Dcab:7678 >>> table {'Dcab': 7678, 'Sjored': 4127, 'Jack': 4098} >>> print('Jack:{Jack:d};Sjored:{Sjored:d};Dcab:{Dcab:d}'.format(**table)) Jack:4098;Sjored:4127;Dcab:7678 >>> import math >>> print('The value of PI is approximately %5.3f.'%math.pi) The value of PI is approximately 3.142. 

你可能感兴趣的:(Python[十一]:Format)