☆☆ 新着記事 ☆☆

2018年10月4日木曜日

Python 出力記法 (%s, %d, format) 等

%記法
%記法は%演算子を使って変数で置き換える方法です。

%dや%sなどの変換指定文字を利用して文字列と変数を出力します。

◆%記法の書式は以下の通り。

print(‘任意の文字列  %s  任意の文字列’) % 変数 #変数の中身が文字列のとき
print(‘任意の文字列  %d 任意の文字列’) % 変数 #変数の中身が整数のとき


変数の中身が文字列のときの「%s」、整数の数値のときの「%d」の2つがとくによく使われます。

answer = 50
print('答え:%d' % answer)

実行結果:
答え:50

** %記法で複数の変数を出力したい場合は、タプル型を利用。
name = 'Tanaka'
point = 80
print('%sの得点: %d ' % (name, point))
実行結果:
Tanakaの得点:80

◆format メソッドによる記述
a = 123
b = 'abc'

print('{} and {}'.format(a, b))
# 123 and abc

print('{first} and {second}'.format(first=a, second=b))
# 123 and abc


print(f'{a} and {b}')
# 123 and abc

print(f'{a} and {b}')
# 123 and abc

print(f"{a} and {b}")♯Single QuoteによるDobule Quote (or simple Dobule Quote)
# 123 and abc

print(f'''{a} and {b}''') ♯Single QuoteによるTriple Quote (or simple Triple Quote)
# 123 and abc

print(f"""{a} and {b}""")♯Double QuoteによるTriple Quote
# 123 and abc




参考)
http://programming-study.com/technology/python-print/

0 件のコメント:

コメントを投稿