LoginSignup
2
1

Pythonのf-stringについて(桁数を変数で指定する場合)

Posted at

本記事の背景

Pythonは常に進化している言語で、C言語の「%d」みたいな指定から専用の「.format()」で指定する方法のほかに、f-stringで指定できるのがほかの言語にない特徴である(個人的な感想)

f-stringの基本

f'{<変数名>:書式}'

書式については、やや複雑な仕様になっているため、細かい解説を参照してほしい。
https://prograshi.com/language/python/python-f-string/

以下は10進から2進へ変換する例

number = 8
s = f'{number:b}'
print(s)
# output(10進から2進)
1000

桁数の指定

x = 1.23456789
res = f'{x:.2f}'
print( res )

#出力
# '1.23'

桁数を変数で指定する方法

2進数の桁数に合わせて、表示する数字を全体に反映させたい場合は、
{}を2重で書けます。
なかなか大胆な発想です。

number = 16
s = f'{number:b}'
bin_len = len(s)
# f-stringを2重で指定する例
for n in range(1, number+1):
    s = f'{n:{bin_len}} {n:{bin_len}o} {n:{bin_len}X} {n:{bin_len}b}'
    print(s)

出力結果

    1     1     1     1
    2     2     2    10
    3     3     3    11
    4     4     4   100
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8    10     8  1000
    9    11     9  1001
   10    12     A  1010
   11    13     B  1011
   12    14     C  1100
   13    15     D  1101
   14    16     E  1110
   15    17     F  1111
   16    20    10 10000
2
1
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
1