2
2

More than 3 years have passed since last update.

Format表記

Last updated at Posted at 2020-06-19
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 こちらは数が多くなると面倒
print('{0} {2}'.format(*t)) #1 3 展開
print('{0} {2}'.format(1, 2, 3)) #1 3 上と同じ

d = {'name': 'jun', 'family': 'sakai'}
print('{0[name]} {0[family]}'.format(d)) #jun sakai
print('{name} {family}'.format(**d)) #jun sakai 展開
print('{name} {family}'.format(name='jun', family='sakai')) #jun sakai 上と同じ

print('{:<30}'.format('left')) #全体が30文字で左寄りに表示
print('{:>30}'.format('right')) #全体が30文字で右寄りに表示
print('{0:^30}'.format('center')) #全体が30文字で中央寄りに表示
print('{0:*^30}'.format('center')) #全体が30文字で中央寄りに表示、*で隙間を埋める
print('{name:*^30}'.format(name='center')) #上と同じ
print('{name:{fill}{align}{width}}'.format(name='center', fill='*', align='^', width=30)) #上と同じ
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,0bなどの表示が消える

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

実行結果:

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 
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2