初心者のためのpython入門

自分がつまづいたところやつまづきやすいところを中心に書いていきます。また、役に立つライブラリの紹介などをしていきます。

入出力~出力編~

前書き

今回から入出力について説明していきます。

print

printは、今まで使用して来たように値を出力します。サンプルを見ましょう。

# sample.py
print('Hello World')
print('Hello', 'World', sep=',') # ,で要素を区切りながら出力
print('Hello World', end='!') # 終了が開業ではなく!になる
print() # 改行

number = 100
print('number = %d' % number) # %を使った記法
print('number = {0}'.format(number)) # formatを使った記法
# 出力結果
Hello World
Hello,World
Hello World!
number = 100
number = 100

上記の例が基本的な使い方になります。sep引数やend引数を指定することができます。%記法よりもformat記法を使うことの方が多いので、format記法を使うようにしましょう。

format記法を詳しく

format記法での出力をもう少し詳しく説明します。サンプルを見ましょう。

# sample.py
# 順序引数を使った記法
print('{0} and {1}'.format('Men', 'Women'))
print('{1} and {0}'.format('Women', 'Men'))

# キーワード引数を使った記法
print('{language} is {adjective}.'.format(language='Python', adjective='interesting'))

# 順序引数とキーワード引数を使った記法
print('{0}, {1}, and {other}.'.format('TensorFlow', 'Keras', other='PyTorch'))

# フォーマット指定子の利用
contents = 'Python'
print('This is {}.'.format(contents))
print('This is {!r}.'.format(contents)) # 'Python'と''が表示される

print('10 / 3 ≒ {0:.2f}'.format(10/3))  # 小数点第2位まで表示

table = {'J': 11, 'Q': 12, 'K': 13}
for name, phone in table.items():
    print('{0:5} ==> {1:5d}'.format(name, phone)) # 5文字以上の幅で表示

# その他の記法
print('Jack: {0[J]:d}; Queen: {0[Q]:d}; King: {0[K]:d}'.format(table)) # 辞書のキーで参照
print('Jack: {J:d}; Queen: {Q:d}; King: {K:d}'.format(**table)) # **記法
# 実行結果 適宜改行を入れています
Men and Women
Women and Men

Python is interesting.

TensorFlow, Keras, and PyTorch.

This is Python.
This is 'Python'.

10 / 3 ≒ 3.33

J     ==>    11
Q     ==>    12
K     ==>    13

Jack: 11; Queen: 12; King: 13
Jack: 11; Queen: 12; King: 13

実行結果は上記のようになります。フォーマット指定子は数多くの組み合わせがあるので必要に応じて調べてみてください。以下に代表的なものは挙げておきます。

代表的な変換型(%○)

意味
%d 符号付10進数
%f 浮動小数点数
%e, %E 指数表記の浮動小数点数
%r 文字列
%s 文字列

%rと%sには微妙な違いあります。%rはオブジェクトをrepr()で変換したものであり、%sはオブジェクトをstr()で変換したものになります。この違いは発展的な内容なので、詳しい説明は今後致します。

位置指定と0埋め(:○, :0)

記号 意味
< 左寄せ
^ 中央寄せ
> 右寄せ
0 0で空白を埋める
print('{:0>10}'.format(12345)) # 0000012345

進数

進数 意味
b 2進数
o 8進数
d 10進数
x 16進数(小文字)
X 16進数(大文字)
print('{:04b}'.format(12)) # 1100
print('{:04o}'.format(12)) # 0014
print('{:04d}'.format(12)) # 0012
print('{:04x}'.format(12)) # 000c
print('{:04X}'.format(12)) # 000C
後書き

お疲れ様でした。これで好きな形にデータを整えて出力することができると思います。次回は、入力について説明します。