0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python初心者】文字列フォーマットまとめ(format() と f文字列)

Posted at

Pythonでの文字列フォーマットは、format() メソッドや f文字列(f-string)を使うことで、出力の見た目を整えることができます。
本記事では、文字列フォーマットの基本的な使い方と、よく使われるフォーマット指定子を分かりやすく整理しています。


Pythonの文字列フォーマット方法の種類

Pythonでは、文字列を整形する方法が主に3つあります:

方法 特徴 対応バージョン
% フォーマット 古いスタイル。C言語に似ている Python 2〜3(非推奨寄り)
str.format() 柔軟で汎用的な方法。試験でもよく出る Python 2.6〜
f文字列(f-string) 直感的で簡潔。Python 3.6以降の主流 Python 3.6〜

この記事では主に、str.format() と f文字列を取り上げて比較しながら解説します。
% フォーマットも補足として紹介します。


1. format() の基本と使い方

1-1. 位置引数とキーワード引数

# 位置引数
"{}さんは{}歳です".format("田中", 28)
# → '田中さんは28歳です'

# キーワード引数
"{name}さんは{age}歳です".format(name="佐藤", age=30)
# → '佐藤さんは30歳です'

1-2. インデックス指定

"{0}さんは{1}歳、{0}さんの趣味は{2}です".format("田中", 28, "読書")
# → '田中さんは28歳、田中さんの趣味は読書です'

2. format() で使えるフォーマット指定子

2-1. fill(埋め)、align(寄せ)、width(フィールド幅)

# 右寄せ(幅5)
"{:>5}".format("a")
# → '    a'

# 左寄せ(幅5)
"{:<5}".format("a")
# → 'a    '

# 中央寄せ(幅5)
"{:^5}".format("a")
# → '  a  '

# 埋め文字0+右寄せ(幅6)
"{:0>6}".format(42)
# → '000042'

2-2. sign(符号)

# 正負どちらも表示
"{:+}".format(3)
# → '+3'

# 正のとき空白
"{: }".format(3)
# → ' 3'

# 負のときのみマイナス
"{:-}".format(3)
# → '3'

2-3. ,(3桁区切り)

"{:,}".format(1234567)
# → '1,234,567'

2-4. .precision(小数点以下の桁数)

"{:.2f}".format(3.14159)
# → '3.14'

"{:.1%}".format(0.876)
# → '87.6%'

2-5. type(変換型)

"{:d}".format(42)      # 整数
# → '42'

"{:.2f}".format(3.14)  # 小数(2桁)
# → '3.14'

"{:.1%}".format(0.85)  # パーセント
# → '85.0%'

"{:s}".format("abc")   # 文字列
# → 'abc'

3. f文字列(f-string)の基本と使い方

3-1. 基本構文(Python 3.6以降)

name = "鈴木"
age = 25
f"{name}さんは{age}歳です"
# → '鈴木さんは25歳です'

3-2. フォーマット指定子の使い方(format() と同じ)

# 幅・埋め文字・寄せ
value = 42
f"{value:0>6}"
# → '000042'

# 小数点以下2桁
pi = 3.14159
f"{pi:.2f}"
# → '3.14'

# カンマ区切り
num = 1234567
f"{num:,}"
# → '1,234,567'

# 符号表示
f"{+3:+}"
# → '+3'

# パーセント表示
rate = 0.876
f"{rate:.1%}"
# → '87.6%'

4. format() と f文字列の比較

機能 format() 形式 f文字列形式
基本書式 "{:.2f}".format(3.14) f"{3.14:.2f}"
複雑な埋め込み 可(式や変数もOK)
可読性 やや長い より直感的で読みやすい
Pythonバージョン 2.6以降 3.6以降

5. 補足:%による旧スタイルのフォーマット

"%sさんは%d歳です" % ("田中", 28)
# → '田中さんは28歳です'
  • %s: 文字列
  • %d: 整数
  • %f: 小数(%.2f で2桁)

現在は format()f文字列が推奨されています。

6. まとめ

  • format() も f文字列も、フォーマット指定子の書き方は同じ
  • fill(埋め)、align(寄せ)、width(フィールド幅)を組み合わせて表示を整形
  • 精度、符号、カンマ区切り、型指定なども柔軟に対応可能
  • f文字列はPython 3.6以降の推奨スタイルで、可読性も高い
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?