LoginSignup
39
53

More than 5 years have passed since last update.

pythonのprint内で変数に代入されている数字や文字を表示する

Last updated at Posted at 2015-08-25

Python初学者にとってprint文で変数とテキスト同時に表示したいと思って検索してもなかなかでないので簡単ではあるがここで解説したいと思う。

変数xに代入された文字をprintで表示する

ここでは3つの方法を解説する。
1.テキスト+変数を表記する
2.%dや%sといった変換指定文字を使う
3.format関数を使う

1.テキスト+変数を表記する

test1.py

x = 3
print "xは"+str(x)+"です"

test1.py出力
'xは3です'

Xをstring型に変換するのを忘れないようにする。

2.%dや%sといった変換指定文字を使う

test2.py

x = 3
print "xは%dです" % x

test2.py出力
'xは3です'

またlocals()を使って以下のような書き方もできるらしいです。

test2_1.py

x = 3
print "xは%(x)sです" % locals()
test2_1.py出力
'xは3です'

3.format関数を使う

test3.py

x = 3
print "xは{0}です".format(x)

test3.py出力
'xは3です'
test3_1.py

x = 3
print "xは{x}です".format(**locals())

test3_1.py出力
'xは3です'

個人的には.format()が便利だと思う。formatは変数の型を気にしなくて良いし、変数が増えてきたら{0},{1}...というように増やしていけばいいだけ。後ろのformatは(変数1,変数2...)としておけば良い。

追記 2015/9/24にご指摘がありましたので訂正しました

39
53
2

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
39
53