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"のような"引数指定子"を含みます。

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

# これは "Hello, John!" を出力します。
name = "John"
print("Hello, %s!" % name)

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

# これは "John is 23 years old." を出力します。
name = "John"
age = 23
print("%s is %d years old." % (name, age))

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

# これは "A list: [1, 2, 3]" を出力します。
mylist = [1,2,3]
print("A list: %s" % mylist)

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

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

%d - 整数

%f - 浮動小数点数

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

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

Exercise

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

data = ("John", "Doe", 53.44) format_string = "Hello" print(format_string % data) data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s." print(format_string % data) #test_output_contains("Hello John Doe. Your current balance is $53.44.", no_output_msg= "Make sure you add the `%s` in the correct spaces to the `format_string` to meeet the exercise goals!") test_object('format_string') success_msg('Great work!')

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