Format notation

t = (1, 2, 3)
print('{0[0]} {0[2]}'.format(t)) #1 3
print('{t[0]} {t[2]}'.format(t=t)) #1 3
print('{} {}'.format(t[0], t[2])) #1 3 This is troublesome when the number increases
print('{0} {2}'.format(*t)) #1 3 Deployment
print('{0} {2}'.format(1, 2, 3)) #1 3 Same as above

d = {'name': 'jun', 'family': 'sakai'}
print('{0[name]} {0[family]}'.format(d)) #jun sakai
print('{name} {family}'.format(**d)) #jun sakai deployment
print('{name} {family}'.format(name='jun', family='sakai')) #jun sakai Same as above

print('{:<30}'.format('left')) #The whole is 30 characters and is displayed to the left
print('{:>30}'.format('right')) #The whole is 30 characters and is displayed to the right
print('{0:^30}'.format('center')) #The whole is 30 characters and is displayed near the center
print('{0:*^30}'.format('center')) #The whole is displayed in 30 characters near the center,*Fill the gap with
print('{name:*^30}'.format(name='center')) #Same as above
print('{name:{fill}{align}{width}}'.format(name='center', fill='*', align='^', width=30)) #Same as above
print('{:,}'.format(123456789)) #123,456,789
print('{:+f} {:+f}'.format(3.14, -3.14)) #+3.140000 -3.140000
print('{:f} {:f}'.format(3.14, -3.14)) #3.140000 -3.140000
print('{:-f} {:-f}'.format(3.14, -3.14)) #3.140000 -3.140000
print('{:.2%}'.format(19/22)) #86.36%
print('{}'.format(19/22)) #0.8636363636363636

print(int(100), hex(100), oct(100), bin(100)) #100 0x64 0o144 0b1100100
print('{0:d} {0:#x} {0:#o} {0:#b}'.format(100))  #100 0x64 0o144 0b1100100
print('{0:d} {0:x} {0:o} {0:b}'.format(100))  #100 64 144 1100100 0x,0o,Display such as 0b disappears

for i in range(20):
    for base in 'bdX':
        print('{:5{base}}'.format(i, base=base), end=' ')
    print()

Execution result:

1 3
1 3
1 3
1 3
1 3
jun sakai
jun sakai
jun sakai
left                          
                         right
            center            
************center************
************center************
************center************
123,456,789
+3.140000 -3.140000
3.140000 -3.140000
3.140000 -3.140000
86.36%
0.8636363636363636
100 0x64 0o144 0b1100100
100 0x64 100 0b1100100
100 64 100 1100100
    0     0     0 
    1     1     1 
   10     2     2 
   11     3     3 
  100     4     4 
  101     5     5 
  110     6     6 
  111     7     7 
 1000     8     8 
 1001     9     9 
 1010    10     A 
 1011    11     B 
 1100    12     C 
 1101    13     D 
 1110    14     E 
 1111    15     F 
10000    16    10 
10001    17    11 
10010    18    12 
10011    19    13 

Recommended Posts

Format notation
Comprehension notation
String format
String format 2
Comprehension notation
Python string format
Python string format
Dictionary comprehensive notation
format in python
Visualize N-ary notation