Python の f-string による文字列フォーマット
f-strings は変数や式をそのまま文字列に入れられます。コロンの後ろに書く書式指定子で、小数点以下、幅、揃え、区切りを調整できます。
の f-string による文字列フォーマットとは?
f-strings は変数や式をそのまま文字列に入れられます。コロンの後ろに書く書式指定子で、小数点以下、幅、揃え、区切りを調整できます。
Python の f-strings と書式指定子で読みやすい出力を作ります。
どのような場面で使う?
- 実行できるコードでPython構文を学ぶ。
- より大きな課題に必要な基礎を身につける。
- ローカル環境なしでアイデアを試す。
サンプルコード
main.py
name = "Lin"
score = 92.456
items = 3
# f-strings put expressions inside {} directly in the text.
print(f"{name} scored {score} points")
# Format specifiers after a colon control how values look.
print(f"Rounded: {score:.1f}")
print(f"Price: ${19.5:.2f}")
print(f"Padded: [{items:>5}] [{items:<5}] [{items:^5}]")
print(f"Thousands: {1234567:,}")
print(f"Percent: {0.875:.0%}")
# Any expression works, including calls and arithmetic.
print(f"{name.upper()} has {items * 2} tickets")
# A table with aligned columns.
for product, price in [("Tea", 2.5), ("Coffee", 3.75)]:
print(f"{product:<8}{price:>6.2f}")
期待される出力
Lin scored 92.456 points
Rounded: 92.5
Price: $19.50
Padded: [ 3] [3 ] [ 3 ]
Thousands: 1,234,567
Percent: 88%
LIN has 6 tickets
Tea 2.50
Coffee 3.75
仕組み
.1f は小数第 1 位に丸めます。>5 と <5 は 5 文字の中で揃えます。, は桁区切りを入れ、.0% は小数をパーセントで表示します。
値を変更し、PythonをインストールせずにCodeUtilityオンラインPythonコンパイラで実行できます。
練習問題
入力値と境界ケースを変更し、より大きなデータでも動作を確認してください。
- 実行前に出力を予測する。
- 空または不正な入力を処理する。
- 処理を関数化し、テストケースを追加する。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- Multiplication Table Row List the first multiples of a number. 簡単
- Count Uppercase Letters Count the capital letters in a text. 簡単
- Initials From a Name Build uppercase initials from a full name. 簡単