0
0

More than 3 years have passed since last update.

Python formatのあれこれ(省略Ver)

Posted at

この記事ではPythonの基礎であるformatについてまとめていきます。

もっと詳しくみたいという方はこちらをみてください!

Python formatのあれこれ

それでは早速みていきましょう!

formatをみてみる

name = "かるでね"
print("私の名前は{}です。".format(name))   # 私の名前はかるでねです。

複数の変数を扱う

name = "かるでね"
age = 21
like = "Python"

print("私の名前は{}です。年齢は{}歳です。{}が好きです。".format(name, age, like))   
# 私の名前はかるでねです。年齢は21歳です。Pythonが好きです。

print("私の名前は" + name + "です。年齢は" + age + "歳です。" + like + "が好きです。")  
# 私の名前はかるでねです。年齢は21歳です。Pythonが好きです。

番号で指定

name = "かるでね"
age = 21
like = "Python"

print("私の名前は{0}です。私の名前は{0}です。私の名前は{0}です。".format(name, age, like))   
# 私の名前はかるでねです。私の名前はかるでねです。私の名前はかるでねです。

print("私の名前は{0}です。私の名前は{0}です。私の名前は{0}です。".format(name))    # ②
# 私の名前はかるでねです。私の名前はかるでねです。私の名前はかるでねです。

キーワード指定


name = "かるでね"
like = "Python"

print("私の名前は{name}です。{like}が好きです。".format(name=name, like=like))   
# 私の名前はかるでねです。Pythonが好きです。

もっと簡単に書こう


name = "かるでね"
like = "Python"

print(f"私の名前は{name}です。{like}が好きです。")   
# 私の名前はかるでねです。Pythonが好きです。

応用

小数点

import math

pi = math.pi

print("円周率: {pi:.2f}".format(pi=pi))   # 円周率: 3.14
print("円周率: {pi:.3f}".format(pi=pi))   # 円周率: 3.142
print("円周率: {pi:.5f}".format(pi=pi))   # 円周率: 3.14159

カンマ区切り

prace1 = 10000000
prace2 = 100000000000000

print("prace1: {:,}".format(prace1))   # prace1: 10,000,000
print("prace2: {:,}".format(prace2))   # prace2: 100,000,000,000,000

%


name = "かるでね"
like = "Python"

print("私の名前は%sです。" % name)   # 私の名前はかるでねです
print("私の名前は%sです。%sが好きです。" % (name, like))   # 私の名前はかるでねです。Pythonが好きです。

今回は「fotmat」について確認してきました。

pythonで何か作るにしても、機械学習をやるにしても「fotmat」は使われるので今後は積極的に使用していきましょう。

Twitterでもお役立ち情報を発信しているのでぜひ!

それでは!

0
0
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
0
0