Python String format() 例で説明する
Python String format() とは何ですか?
Python String format() は、最終的な文字列内の有効な値を持つプレースホルダーで文字列を置換、置換、または変換するために使用される関数です。これは Python 文字列クラスの組み込み関数であり、フォーマットされた文字列を出力として返します。文字列内のプレースホルダーは中括弧で定義されます。
たとえば、「Guru99 {} へようこそ」.format('ここの値')。
Python の format() 関数の構文
templatestring.format(val1, val2...)
パラメータ
val1, val2 … : 中括弧 {} の形式のプレースホルダーを持つ、指定されたテンプレート文字列内で置換する必要がある値。プレースホルダーには、文字列、キーと値のペア、整数、浮動小数点数、文字などを使用できます。
戻り値
中括弧で囲まれたプレースホルダーの代わりに有効な値が置き換えられた、最終的な文字列が返されます。
プレースホルダー
テンプレート文字列内のプレースホルダーは、中括弧を使用して表されます。 {}。プレースホルダーは空の {} にすることも、 {name} などの変数を含めることも、{0} 、 {1} などの数値インデックスを含めることもできます。
string format() はどのように機能するのでしょうか?
Python String format() メソッドは、元の文字列をスキャンしてプレースホルダーを探します。プレースホルダーには、空の中括弧 ({})、位置引数を使用できます。つまり、文字列には、{0}、{1} などのインデックス 0、1 のプレースホルダーを含めることができます。
キーワード引数の場合、変数名は中括弧内に表示されます (例: {name}、{age})。空の中括弧の場合、フォーマットの値が中括弧内で順番に置き換えられます。
最初の値は最初の空の中括弧に置き換えられ、その後に次の値が続きます。位置引数の場合、インデックスは 0 から始まります。値はカンマで区切られた形式で使用でき、0th の値は形式内の最初の値を指します。以下同様です。
キーワード引数の場合、つまりプレースホルダー内で変数を使用する場合、必要に応じて形式内で値の順序を指定できます。
値は format() 内に存在する変数名に基づいて置き換えられるため、ここでは順序は重要ではありません。ここでは、文字列内のプレースホルダーを空、位置、キーワードまたは変数を使用して使用する方法の例をいくつか示します。
例: 空のプレースホルダーが文字列値に置き換えられる
以下の例では、文字列に空の中括弧 ({}) が含まれています。形式に指定された値は中括弧 ({}) 内で置き換えられます。
置換する値は文字列です。
例:
Python の文字列書式設定を使用して、中括弧 ({}) を文字列値に置き換えます。値はformat(“Guru99”)に与えられます。実行すると、中括弧 {} が Guru99 に置き換えられ、最終的な文字列が「Welcome to Guru99 チュートリアル」として取得されます。
print ("Welcome to {} tutorials".format("Guru99"))
出力:
Welcome to Guru99 tutorials
例: 空のプレースホルダーは数値に置き換えられます
以下の例では、元の文字列内の数値を置き換えます。数値が必要な箇所に中括弧({})が追加されます。実行すると、空の中括弧 ({}) が数値に置き換えられます。
例 :
format() を使用して文字列内に数値を挿入することもできます。この例では、空のプレースホルダー {} を format() 内に存在する番号 99 に置き換える方法を示します。
print ("Welcome to Guru{} Tutorials".format("99"))
出力:
Welcome to Guru99 Tutorials
例: プレースホルダー内での変数またはキーワード引数の使用
以下の例に示すように、中括弧内の変数を使用することもできます。変数は format() 内で定義されます。したがって、実行すると、変数に割り当てられた値が元の文字列内で置き換えられます。
例:
{name} {num} のように中括弧内で変数を使用できます。name 変数と num 変数の値は、format(name=”Guru”, num=”99″) などの形式内で使用できます。 name と num に指定された値は、{name} と {num} 内で置き換えられます。
print ("Welcome to {name}{num} Tutorials".format(name="Guru", num="99"))
出力:
Welcome to Guru99 Tutorials
例: プレースホルダー内でのインデックスまたは位置引数の使用
値は、プレースホルダー内の 0、1、2 などのインデックスを使用して置き換えることができます。以下の例に示すように、値は format() から順に取得されます。
例:
print ("Welcome to {0}{1} Tutorials".format("Guru","99"))
出力:
Welcome to Guru99 Tutorials
例: 文字列内で複数のプレースホルダーを使用する
この例では、複数の空のプレースホルダーを使用します。
例:
この例で使用されている文字列には複数の空のプレースホルダーがあり、各プレースホルダーは format() 内の値を参照します。最初の値は最初のプレースホルダーに置き換えられ、以下同様になります。
print ("{} is {} new kind of {} experience!".format("Guru99", "totally","learning"))
出力:
Guru99 is totally new kind of learning experience!
プレースホルダー内の書式設定
変数またはインデックスを使用して、プレースホルダーを空にすることができることがわかりました。プレースホルダー内で Python 文字列の書式設定を適用することもできます。
フォーマットのリストはこちら
Format | Description | Example |
---|---|---|
:d |
It will give the output in decimal format when used inside the placeholder | print("The binary to decimal value is : {:d}".format(0b0011))
Output:
|
:b |
It will give the output in binary format when used inside the placeholder | print("The binary value is : {:b}".format(500))
Output:
|
:e |
It will give the output in scientific format when used inside the placeholder, the exponent e in the output will be lowercase. | print("The scientific value is : {:e}".format(40))
Output:
|
:E |
It will give the output in scientific format when used inside the placeholder, the exponent E in the output will be uppercase | print("The scientific value is : {:E}".format(40))
Output:
|
:f |
This will output a fixed-point number format. By default, you will get the output of any number with six decimal places. In case you need up to 2 decimal places, use it as. 2f i.e.. a period (.) in front of 2f | print("The value is : {:f}".format(40))
Output:
Example: Showing output upto 2 decimal places.
Output:
|
:o |
This will output octal format | print("The value is : {:o}".format(500))
Output:
|
:x |
This will output hex format in lowercase | print("The value is : {:x}".format(500))
Output:
|
:X |
This will output hex format in uppercase. | print("The value is : {:X}".format(500))
Output:
|
:n |
This will output number format. | print("The value is : {:n}".format(500.00))
Output:
|
:% |
This will give the output in a percentage format. By default it will give 6 decimal places for the percentage output, in case you don’t want any decimal value you can use period with 0 i.e (:.0%). |
print("The value is : {:%}".format(0.80))
Output:
This example shows how to skip the decimal places by using {:.0%} inside the placeholder.
|
:_ |
This will output an underscore as a thousand separator. It is available from python 3.6+. | print("The value is {:_}".format(1000000))
Output:
|
:, |
This will output comma as a thousands separator | print("The value is : {:,}".format(1000000))
Output:
The comma(,) is added , as a thousand separator as shown in the output. |
: |
This will add a space before any positive numbers | This example shows how to add space or padding before the given number. The number 5 indicates the space count you want before the number.
Output:
|
:- |
This will add a minus sign before negative numbers | The example shows how to get the output with a minus (-) sign before the number using {:-}.
Output:
|
:+ |
You can use plus sign to indicate the number is positive | The example shows how to get the output with a plus (+) sign before the number using {:+}.
Output:
|
:= |
The equal to is used to place the +/- sign on the left side. | The example shows how to get the output with a plus (+/-) sign before equal to sign using {:=}.
Output:
|
:^ |
This will center align the final result | The example shows to use {:^} to center align the text. The number 10 is used to add 10 spaces to show the center-aligned when the value is replaced.
Output:
Here, you can use 10 that will add 10 spaces in the final text, and the value to be replaced will be center-aligned between the 10 spaces. The spaces of 10 are added just to show the center alignment of the replaced value. |
:> |
This will right-align the final result | The space of 10 is added using (:>10), and the value replaced is right-aligned.
Output:
|
:< |
This will left align the final result | The space of 10 is added using (:<10), and the value replaces is left aligned.
Output:
|
format() でクラスを使用する
この例では、クラスを作成し、そのクラスのオブジェクトを .format Python メソッド内で使用します。プレースホルダーは、クラス オブジェクトを使用するクラス プロパティまたはメンバーを参照します。
例 :
クラスは、format(c=MyClass()) 内で呼び出されます。オブジェクト c は、クラス MyClass() 内のプロパティとメソッドへの参照を持ちます。
class MyClass:
msg1="Guru"
msg2="Tutorials"
print("Welcome to {c.msg1}99 {c.msg2}!".format(c=MyClass()))
出力:
Welcome to Guru99 Tutorials!
format() で辞書を使用する
以下の例に示すように、format() 内で辞書を使用することもできます。
my_dict = {'msg1': "Welcome", 'msg2': 'Guru99'}
print("{m[msg1]} to {m[msg2]} Tutorials!".format(m=my_dict))
出力:
Welcome to Guru99 Tutorials!
パディング変数の置換
string.format() メソッドを使用すると、文字列内にプレースホルダーを使用してパディングやスペースを追加できます。
例 :
以下の例では、format() を使用してプレースホルダー内にスペースを追加します。スペースを追加するには、コロン(:)の後の中括弧内にスペースの数を指定する必要があります。したがって、プレースホルダーは {:5} のようになります。
print("I have {:5} dogs and {:5} cat".format(2,1))
出力:
I have 2 dogs and 1 cat
プレースホルダー内にインデックスを指定することもできます (例: {0:5})。0 は形式内の最初の値を指します。
print("I have {0:5} dogs and {1:5} cat".format(2,1))
出力:
I have 2 dogs and 1 cat
まとめ
- Python 文字列クラスには、format() と呼ばれる重要な組み込みコマンドが用意されており、最終的な文字列内の有効な値を持つプレースホルダーで文字列を置換、置換、または変換するのに役立ちます。
- 文字列モジュール Python 内のプレースホルダーは、「Welcome to Guru99 {}」.format('value here') のように中括弧で定義されます。
- プレースホルダーは空の {} にすることも、 {name} などの変数を含めることも、{0} 、 {1} などの数値インデックスを含めることもできます。
- プレースホルダー内で Python の文字列書式設定を使用すると、パディングの追加、中央揃え、および数値の書式設定にも役立ちます。