Python は広く使用されているプログラミング言語であり、文字列の書式設定はその非常に基本的かつ重要な機能の 1 つです。ただし、開発プロセス中に、タグの不適切な使用や文法エラーなどのさまざまな要因が原因で、文字列の書式設定エラーが発生することがあります。この記事では、Python の文字列フォーマット エラーを解決する方法について説明します。
1. Python の文字列フォーマット方法を理解する
Python では、文字列をフォーマットする方法が 3 つあります: パーセント記号 (%) メソッド、string.format() 関数メソッド、および新しい f- Python3の文字列メソッド。このうち、最初の 2 つのメソッドが最もよく使用されますが、f-string は Python 3.6 バージョンで追加された新しいメソッドであり、比較的新しいです。
1. パーセント記号 (%) メソッド
パーセント記号 (%) メソッドは、Python における最も初期かつ最も古典的な文字列書式設定メソッドであり、その使用法は次のとおりです:
name = 'Tom' age = 18 score = 95.8 print('%s is %d years old, and his score is %.1f.' % (name, age, score))
出力結果:
Tom is 18 years old, and his score is 95.8.
2. String.format() 関数メソッド
String.format() 関数メソッドは Python の 2 番目の文字列書式設定メソッドであり、その使用法は次のとおりです。 ##
name = 'Tom' age = 18 score = 95.8 print('{} is {} years old, and his score is {:.1f}.'.format(name, age, score))出力結果:
Tom is 18 years old, and his score is 95.8.3.f-stringメソッドPython3.6バージョンではf-stringメソッドが追加されており、使用方法は以下の通りです。 ##
name = 'Tom' age = 18 score = 95.8 print(f'{name} is {age} years old, and his score is {score:.1f}.')
出力結果:
Tom is 18 years old, and his score is 95.8.
2. 一般的な Python 文字列フォーマット エラーと解決策
1. マーカー使用エラー
文字列フォーマットでは、マーカーはとても重要です。一般的なタグには、%s、%d、%f などが含まれます。このうち、%s は文字列、%d は整数、%f は浮動小数点数を表します。
間違ったタグを使用するとエラーが発生します。例:
name = 'Tom' age = 18 score = 95.8 print('%s is %d years old, and his score is %d.' % (name, age, score))
出力結果:
TypeError: %d format: a number is required, not float
これは、スコアが %d マーカーを使用しているためですが、スコアは浮動小数点数であるため、%f マーカーを使用する必要があります。したがって、コードを次のように変更する必要があります:
name = 'Tom' age = 18 score = 95.8 print('%s is %d years old, and his score is %.1f.' % (name, age, score))
出力結果:
Tom is 18 years old, and his score is 95.8.
string.format() 関数または f-string メソッドを使用して、タグ使用エラーを回避することもできます。
2. パラメータの不一致
文字列をフォーマットするときは、渡されるパラメータの数が対応するマーカーの数と一致することを確認する必要があります。パラメータが多すぎたり少なすぎたりするとエラーが発生します。例:
name = 'Tom' print('%s is %d years old.' % (name))
出力結果:
TypeError: not enough arguments for format string
これは、パラメータを 1 つだけ渡したが、マーカーが 2 つあるためです。コードを次のように変更する必要があります。
name = 'Tom' age = 18 print('%s is %d years old.' % (name, age))
出力結果:
Tom is 18 years old.
3. 構文エラー
構文エラーは、Python でよくあるエラーの 1 つです。特に文字列の書式設定では、括弧や引用符などの記号を誤って使用すると、構文エラーが発生しやすくなります。例:
print('My name is {}. I'm {} years old.' .format('Tom', 18))
出力結果:
File "<ipython-input-5-24fc64aa88e2>", line 1 print('My name is {}. I'm {} years old.' .format('Tom', 18)) ^ SyntaxError: invalid syntax
これは、上記の文字列で 2 つの一重引用符が使用されているため、解析エラーが発生します。コードは次のように変更する必要があります:
print("My name is {}. I'm {} years old." .format('Tom', 18))
出力結果:
My name is Tom. I'm 18 years old.
4. まとめ
文字列の書式設定は Python の非常に基本的かつ重要な機能です。その解決方法をマスターしてください。 Python 文字列のフォーマットエラーにより、コードの品質が向上する可能性があります。文字列の書式設定を使用する場合は、Python の文字列の書式設定方法を理解し、マーカーの誤った使用、パラメータの不一致、構文エラーなどの一般的なエラー タイプを回避する必要があります。エラーが発生した場合は、コードを注意深く調べてエラーを見つけて修正する必要があります。
以上がPython の文字列フォーマットエラーを解決するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

heouttemptemptostoreavure ofthewrongdatatypeinapythonarray、yure counteractypeerror.thisduetothearraymodule'sstricttypeeencultionyを使用します

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

theScriptisrunningwithwrongthonversionduetorectRectDefaultEntertersettings.tofixthis:1)CheckthedededefaultHaulthonsionsingpython - versionorpython3-- version.2)usevirtualenvironmentsbycreatingonewiththon3.9-mvenvmyenv、andverixe

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Dreamweaver Mac版
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

ホットトピック









