LoginSignup
18
11

More than 3 years have passed since last update.

実は奥が深いpythonのprint関数の使い方

Last updated at Posted at 2018-10-11

 はじめに

pythonの基礎として、print関数の扱いについて記載します。

 環境

python3.6
anaconda1.8.7
macOS

 print関数

文字列、変数、計算などの結果を出力する関数。
もともとは、print文という存在でしたが、python3で関数になっています。

 やってみる

>>>print("Hello world!")
Hello world!

print関数では、変数を出力することもできます。

>>> word1 = "hello"
>>> word2 = "world"
>>> print(word1,word2)
hello world

違う型でもOK。

>>> word1 = "hello"
>>> number1 = 4649
>>> print(word1,number1)
hello 4649

コンマで区切ればいくつでも出力可能です。
また通常はスペースで区切られますが、任意のセパレタを指定可能です。

>>> word1 = "hello"
>>> number1 = 4649
>>> print(word1,number1,sep=",")
hello,4649
>>> print(word1,number1,sep=":")
hello:4649

 リストや辞書の出力

リストや辞書型オブジェクトなどの中身も出力できます。

リスト型

>>> ittosanken_list = ["tokyo","kanagawa","saitama","chiba"]
>>> print(ittosanken_list)
['tokyo', 'kanagawa', 'saitama', 'chiba']

セパレタを指定すればアンパックすることもできる

>>> print(*ittosanken_list)
tokyo kanagawa saitama chiba
>>> print(*ittosanken_list,sep='')
tokyokanagawasaitamachiba

リストの中身が全て表示されます。

続いて辞書型オブジェクト。
辞書のkeyとvalueの両方が出力されます。

>>> shopping_dict = {"milk":200, "natto":150, "tofu":100}
>>> print(shopping_dict)
{'milk': 200, 'natto': 150, 'tofu': 100}

 print関数のその他

お気づきのように、明示されていないものの、末尾には改行が入っているので
プライマリプロンプトは出力の次の行に移動しています。

>>> print("hello world!")
hello world!
>>> 

以下のようにendオプションで空指定することで、末尾の改行を削除することができます

>>> print("Hello world!",end="")
Hello world!>>>

 formatメソッド

formatを使うと、文字列の中に変数を埋め込むことが出来ます。

formatを使用すればprint関数で変数の値を出力することができます。

>>> print("I eat {}.".format("eggs"))
I eat eggs.

引数を複数指定し対応する {} を記述すると複数の要素を埋め込める。
引数の数と {} の数は同一であることに注意が必要

>>> print("area: {}, age {}.".format("chiba", 33))
area: chiba, age 33.

{} の中に引数に対応する数を指定すると、指定した値を埋め込める。

>>> print("{0}, {1}, {0}".format("chiba", "saitama"))
chiba, saitama, chiba

formatの引数に辞書を指定。
{} の中には指定する引数の数と辞書の角括弧 [] の中にキー値を指定することで呼び出しができる。

>>> dict = { "area": "chiba", "age": 33 }
>>> print("area: {0[area]}, Age: {0[age]}".format(dict))
area: chiba, Age: 33

※.format()とfstringは数値列であっても埋め込むことができる。

 おわり

まだまだやれることはありますが、また別途記載します。

18
11
1

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
18
11