logo

Python String format() メソッド

format()>メソッドは、開発者がテンプレート文字列内のプレースホルダーに変数と値を埋め込むことで、フォーマットされた文字列を作成できる強力なツールです。この方法は、幅広いアプリケーション向けにテキスト出力を構築するための柔軟で汎用性の高い方法を提供します。 パイソン 文字列フォーマット()関数 複雑な文字列フォーマットをより効率的に処理するために導入されました。その場合、書式設定の概念を使用するたびに print ステートメントを作成するのではなく、一般化された print ステートメントを作成したい場合があります。

Python String Format() 構文

構文: { }.format(値)



パラメーター:

  • 価値 : 整数、浮動小数点数値定数、文字列、文字、または変数を使用できます。

戻り値の型: プレースホルダーの位置にパラメーターとして渡された値を含む書式設定された文字列を返します。

Python の String Format() の例

Python String format() メソッドの簡単なデモンストレーション パイソン。



Python3






name>=> 'Ram'> age>=> 22> message>=> 'My name>is> {>0>}>and> I am {>1>} years> >old. {>1>}>is> my favorite> >number.'.>format>(name, age)> print>(message)>

>

>

出力

My name is Ram and I am 22 years old. 22 is my favorite number.>

.Format() メソッドの使用

組み込み文字列クラスのこのメソッドは、複雑な変数置換と値の書式設定の機能を提供します。この新しい書式設定手法は、よりエレガントであると考えられています。 format() メソッドの一般的な構文は string.format(var1, var2,…) です。ここでは、中括弧を含む文字列をフォーマットする方法を理解しようとします。 パイソン

Python3




txt>=> 'I have {an:.2f} Rupees!'> print>(txt.>format>(an>=> 4>))>

>

>

出力

I have 4.00 Rupees!>

単一のフォーマッタの使用

この例では、 文字列括弧表記 strをデモンストレーションするプログラム。 format() メソッド。フォーマッタは、1 つ以上の置換フィールドと、中括弧のペアで定義されたプレースホルダを挿入することによって機能します。 { } 文字列に変換して呼び出します str.format()

Python3




# using format option in a simple string> print>(>'{}, A computer science portal for geeks.'> >.>format>(>'techcodeview.com'>))> # using format option for a> # value stored in a variable> str> => 'This article is written in {}'> print>(>str>.>format>(>'Python'>))> # formatting a string using a numeric constant> print>(>'Hello, I am {} years old !'>.>format>(>18>))>

>

文字列はすべてのJavaを置き換えます

>

出力

techcodeview.com, A computer science portal for geeks. This article is written in Python Hello, I am 18 years old!>

複数のプレースホルダーを含む文字列 format()

中括弧の複数のペアは、フォーマット中に使用できます。 Pythonの文字列 。文内で別の変数置換が必要であるとします。これは、2 番目の中括弧のペアを追加し、2 番目の値をメソッドに渡すことで実行できます。 Python はプレースホルダーを次の値に置き換えます。 注文。

構文: { } { } .format(値1, 値2)

パラメーター : (値1、値2): 整数、浮動小数点数値定数、文字列、文字、さらには変数を使用できます。唯一の違いは、format() メソッドのパラメーターとして渡される値の数は、文字列内に作成されるプレースホルダーの数と等しくなければならないことです。

エラーと例外:

インデックスエラー : 文字列に追加のプレースホルダーがあり、format() メソッドでそのプレースホルダーの値を渡さなかった場合に発生します。 Python は通常、プレースホルダーにデフォルトのインデックスを次のような順序で割り当てます。 0、1、2、3…。 パラメータとして渡された値にアクセスします。そのため、インデックスにパラメータとして内部に渡された値が含まれていないプレースホルダーに遭遇すると、IndexError がスローされます。

複数のプレースホルダーを使用して str.format() メソッドを示す Python プログラム。

Python3




# Multiple placeholders in format() function> my_string>=> '{}, is a {} science portal for {}'> print>(my_string.>format>(>'techcodeview.com'>,>'computer'>,>'geeks'>))> # different datatypes can be used in formatting> print>(>'Hi ! My name is {} and I am {} years old'> >.>format>(>'User'>,>19>))> # The values passed as parameters> # are replaced in order of their entry> print>(>'This is {} {} {} {}'> >.>format>(>'one'>,>'two'>,>'three'>,>'four'>))>

>

>

出力

techcodeview.com, is a computer science portal for geeks Hi! My name is User and I am 19 years old This is one two three four>

文字列形式() IndexError

プレースホルダーのインデックス エラー数は 4 ですが、渡された値は 3 つだけであることを示す Python プログラム。

Python3




# parameters in format function.> my_string>=> '{}, is a {} {} science portal for {}'> print>(my_string.>format>(>'techcodeview.com'>,>'computer'>,>'geeks'>))>

>

>

出力

IndexError: tuple index out of range>

エスケープシーケンスを使用した文字列のフォーマット

文字列内で 2 つ以上の特別に指定された文字を使用して、文字列をフォーマットしたりコマンドを実行したりできます。これらの文字はエスケープ シーケンスと呼ばれます。アン Python のエスケープ シーケンス バックスラッシュ () で始まります。たとえば、 は、文字 n の一般的な意味が文字通りエスケープされ、別の意味、つまり改行が与えられるエスケープ シーケンスです。

エスケープシーケンス 説明
文字列を新しい行に分割します print('この韻は、やがて説明できるように設計しました 私が知っているすべて')
水平タブを追加します print('時間は 貴重なもの')
バックスラッシュを出力します print('振り子の揺れに合わせて飛んでいくのを見てください')
「」 一重引用符を出力します print('どれだけ頑張ってもダメ')
二重引用符を出力します print('とても非現実的です')
a 鐘のような音を出す print('a')

位置引数とキーワード引数を使用したフォーマッタ

プレースホルダーの場合 { } が空の場合、Python は str.format() を介して渡された値を順番に置き換えます。 str.format() メソッド内に存在する値は、基本的に次のとおりです。 タプル データ型 タプルに含まれる個々の値は、インデックス番号 0 から始まるインデックス番号によって呼び出すことができます。これらのインデックス番号は、元の文字列のプレースホルダーとして機能する中かっこに渡すことができます。

構文: {0} {1}.format(位置引数, キーワード引数)

パラメーター : (位置引数、キーワード引数)

  • 位置引数 整数、浮動小数点数値定数、文字列、文字、さらには変数を使用できます。
  • キーワード_引数 本質的には、パラメータとして渡される値を格納する変数です。

例: 位置キー引数を使用したフォーマッタの使用法を示します。

Python3




# Positional arguments> # are placed in order> print>(>'{0} love {1}!!'>.>format>(>'techcodeview.com'>,> >'Geeks'>))> # Reverse the index numbers with the> # parameters of the placeholders> print>(>'{1} love {0}!!'>.>format>(>'techcodeview.com'>,> >'Geeks'>))> print>(>'Every {} should know the use of {} {} programming and {}'> >.>format>(>'programmer'>,>'Open'>,>'Source'>,> >'Operating Systems'>))> # Use the index numbers of the> # values to change the order that> # they appear in the string> print>(>'Every {3} should know the use of {2} {1} programming and {0}'> >.>format>(>'programmer'>,>'Open'>,>'Source'>,>'Operating Systems'>))> # Keyword arguments are called> # by their keyword name> print>(>'{gfg} is a {0} science portal for {1}'> >.>format>(>'computer'>,>'geeks'>, gfg>=>'techcodeview.com'>))>

>

>

出力

techcodeview.com love Geeks!!  Geeks love techcodeview.com!!  Every programmer should know the use of Open Source programming and Operating Systems  Every Operating Systems should know the use of Source Open programming and programmer  techcodeview.com is a computer science portal for geeks>

Python での型指定

構文の中括弧内にさらに多くのパラメーターを含めることができます。フォーマットコード構文を使用する {フィールド名: 変換} 、 どこ フィールド名 str.format() メソッドの引数のインデックス番号を指定し、変換はデータ型の変換コードを参照します。

%s を使用しています – フォーマット前の str() による文字列変換

Python3




print>(>'%20s'> %> (>'geeksforgeeks'>, ))> print>(>'%-20s'> %> (>'Interngeeks'>, ))> print>(>'%.5s'> %> (>'Interngeeks'>, ))>

>

>

出力

geeksforgeeks Interngeeks  Inter>

%c の使用 - キャラクター フォーマットする前に

Python3




type> => 'bug'> result>=> 'troubling'> print>('I wondered why the program was>%>s me. Then> it dawned on me it was a>%>s .'>%> >(result,>type>))>

>

>

出力

I wondered why the program was troubling me. Thenit dawned on me it was a bug .>

%i の使用 符号付き 10 進整数と %d フォーマット前の符号付き 10 進整数 (基数 10)

Python3




match>=> 12000> site>=> 'Amazon'> print>('>%>s>is> so useful. I tried to look> up mobile>and> they had a nice one that cost>%>d rupees.'>%> (site, match))>

>

>

出力

Amazon is so useful. I tried to lookup mobile and they had a nice one that cost 12000 rupees.>

もう 1 つの便利な型指定

  • %で 符号なし 10 進整数
  • %O 8 進整数
  • f – 浮動小数点表示
  • b – 2進数
  • – 8 進数
  • %バツ – 9 の後に小文字を含む 16 進数
  • %バツ – 9 の後に大文字を含む 16 進数
  • それは – 指数表記

指定することもできます 記号の書式設定 。唯一の変更点は、% の代わりにコロン (:) を使用することです。

配列Javaを返す

たとえば、%s の代わりに {:s} を使用し、%d の代わりに (:d} を使用します)

構文: 文字列 {フィールド名:変換} Example.format(value)
エラーと例外:
値エラー: このメソッドでは型変換時にエラーが発生します。

基数 10 の 10 進整数を浮動小数点数値定数に変換します

Python3




print>(>'This site is {0:f}% securely {1}!!'>.> >format>(>100>,>'encrypted'>))> # To limit the precision> print>(>'My average of this {0} was {1:.2f}%'> >.>format>(>'semester'>,>78.234876>))> # For no decimal places> print>(>'My average of this {0} was {1:.0f}%'> >.>format>(>'semester'>,>78.234876>))> # Convert an integer to its binary or> # with other different converted bases.> print>(>'The {0} of 100 is {1:b}'> >.>format>(>'binary'>,>100>))> print>(>'The {0} of 100 is {1:o}'> >.>format>(>'octal'>,>100>))>

>

>

出力

This site is 100.000000% securely encrypted!! My average of this semester was 78.23% My average of this semester was 78% The binary of 100 is 1100100 The octal of 100 is 144>

タイプ指定エラー

強制実行中の ValueError をデモする 型変換

Python3




# When explicitly converted floating-point> # values to decimal with base-10 by 'd'> # type conversion we encounter Value-Error.> print>(>'The temperature today is {0:d} degrees outside !'> >.>format>(>35.567>))> # Instead write this to avoid value-errors> ''' print('The temperature today is {0:.0f} degrees outside !'> >.format(35.567))'''>

>

>

出力

ValueError: Unknown format code 'd' for object of type 'float'>

パディング置換またはスペースの生成

文字列がパラメータとして渡される場合の間隔のデモ

デフォルトでは、文字列はフィールド内で左詰めで配置され、数値は右詰めで配置されます。コロンの直後に配置コードを配置することで、これを変更できます。

  <   : left-align text in the field   ^   : center text in the field>: フィールド内のテキストを右揃えにします>>

Python3




# To demonstrate spacing when> # strings are passed as parameters> print>(>'{0:4}, is the computer science portal for {1:8}!'> >.>format>(>'techcodeview.com'>,>'geeks'>))> # To demonstrate spacing when numeric> # constants are passed as parameters.> print>(>'It is {0:5} degrees outside !'> >.>format>(>40>))> # To demonstrate both string and numeric> # constants passed as parameters> print>(>'{0:4} was founded in {1:16}!'> >.>format>(>'techcodeview.com'>,>2009>))> # To demonstrate aligning of spaces> print>(>'{0:^16} was founded in {1:<4}!'> >.>format>(>'techcodeview.com'>,>2009>))> print>(>'{:*^20s}'>.>format>(>'Geeks'>))>

>

>

出力:

techcodeview.com, is the computer science portal for geeks ! It is 40 degrees outside! techcodeview.com was founded in 2009!  techcodeview.com was founded in 2009 ! *******Geeks********>

アプリケーション

フォーマッタは通常、データを整理するために使用されます。フォーマッタは、大量のデータを視覚的な方法で整理するために使用すると、その真価が発揮されます。ユーザーにデータベースを表示する場合、フォーマッタを使用してフィールド サイズを増やし、配置を変更すると、出力が読みやすくなります。

例: format() を使用して大規模なデータの構成を示すには

Python3




# which prints out i, i ^ 2, i ^ 3,> # i ^ 4 in the given range> # Function prints out values> # in an unorganized manner> def> unorganized(a, b):> >for> i>in> range>(a, b):> >print>(i, i>*>*>2>, i>*>*>3>, i>*>*>4>)> # Function prints the organized set of values> def> organized(a, b):> >for> i>in> range>(a, b):> ># Using formatters to give 6> ># spaces to each set of values> >print>(>'{:6d} {:6d} {:6d} {:6d}'> >.>format>(i, i>*>*> 2>, i>*>*> 3>, i>*>*> 4>))> # Driver Code> n1>=> int>(>input>(>'Enter lower range :- '>))> n2>=> int>(>input>(>'Enter upper range :- '>))> print>(>'------Before Using Formatters-------'>)> # Calling function without formatters> unorganized(n1, n2)> print>()> print>(>'-------After Using Formatters---------'>)> print>()> # Calling function that contains> # formatters to organize the data> organized(n1, n2)>

>

>

出力:

Enter lower range :- 3 Enter upper range :- 10 ------Before Using Formatters------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 -------After Using Formatters---------  3 9 27 81  4 16 64 256  5 25 125 625  6 36 216 1296  7 49 343 2401  8 64 512 4096  9 81 729 6561>

文字列の書式設定に辞書を使用する

辞書を使用して、書式設定する必要がある文字列内のプレースホルダーに値を解凍します。うちは基本的に使ってます ** 値を解凍します。このメソッドは、SQL クエリの準備中に文字列を置換する場合に役立ちます。

Python3




introduction>=> 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.'> full_name>=> {> >'first_name'>:>'Tony'>,> >'middle_name'>:>'Howard'>,> >'last_name'>:>'Stark'>,> >'aka'>:>'Iron Man'>,> }> # Notice the use of '**' operator to unpack the values.> print>(introduction.>format>(>*>*>full_name))>

>

>

出力:

My name is Tony Howard Stark AKA the Iron Man.>

Python format() とリスト

float 値のリストが与えられた場合、タスクはすべての float 値を 10 進数 2 桁に切り捨てることです。このタスクを実行するためのさまざまな方法を見てみましょう。

Python3




# Python code to truncate float> # values to 2 decimal digits.> > # List initialization> Input> => [>100.7689454>,>17.232999>,>60.98867>,>300.83748789>]> > # Using format> Output>=> [>'{:.2f}'>.>format>(elem)>for> elem>in> Input>]> > # Print output> print>(Output)>

>

>

出力

['100.77', '17.23', '60.99', '300.84']>