Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

文字列のフォーマット


Pythonは、Cスタイルの文字列フォーマットを使用して、新しいフォーマット済みの文字列を作成します。 "%"演算子は、フォーマット文字列とともに、"タプル"(固定サイズのリスト)内に囲まれた変数のセットをフォーマットするために使用されます。このフォーマット文字列は、通常のテキストと一緒に、"%s"や"%d"のような"引数指定子"を含みます。

"名前"という変数にユーザー名が入っていて、そのユーザーに挨拶を出力したいとします。

2つ以上の引数指定子を使用するには、タプル(括弧)を使用します。

文字列でないオブジェクトでも、%s演算子を使ってフォーマットすることができます。そのオブジェクトの"repr"メソッドから返される文字列が文字列としてフォーマットされます。例えば:

知っておくべき基本的な引数指定子を以下に示します:

%s - 文字列(文字列表現を持つ任意のオブジェクト、例えば数字)

%d - 整数

%f - 浮動小数点数

%.<桁数>f - 小数点の右に一定の桁数を持つ浮動小数点数

%x/%X - 16進数表現の整数(小文字/大文字)

Exercise

次の構文を使用してデータを出力するフォーマット文字列を書いてください: Hello John Doe. Your current balance is $53.44.

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy