English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Pythonのstr.formatの詳細解説

前書き

Pythonでは 2.6 新しいバージョンでは、str.format()という新しい文字列フォーマットメソッドが追加されました。基本的な文法は、{}と:を使用して、以前の%。を使用する方法を置き換えます。

フォーマット時の占位符文法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

「マッピング」ルール

位置を通じて

str.format()は、任意の数の引数を受け入れ、引数の順序は指定されません:

>>> "{0} {1}.format("hello", "world")
'hello world'
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}.format("hello", "world")
'world hello world'

キーワード引数を通じて

キーワード引数を使用する場合、文字列には引数名を提供する必要があります:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)
"I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
"I am huoty, age is 18'

オブジェクトの属性を通じて

str.format() 可以直接读取用户属性:

>>> class User(object):
...  def __init__(self, name, age):
...   self.name = name
...   self.age = age
...   
...  def __str__(self):
...   return "{self.name}({self.age})".format(self=self)
...  
...  def __repr__(self):
...   return self.__str__()
...  
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
"I am huoty, age is 18'

通过下标

在需要格式化的字符串内部可以通过下标来访问元素:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8}
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
"I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)

指定转换

可以指定字符串的转换类型:

 conversion ::= "r" | "s" | "a"

其中 "!r" 对应 repr();"!s" 对应 str();"!a" 对应 ascii()。 示例:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2)
"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限定符

填充与对齐

填充通常与对齐一起使用。^、<、> 分别表示居中、左对齐、右对齐,后面跟宽度,: 号后面跟填充字符,只能是一个字符,不指定则默认使用空格填充。

>>> "{:>}8".format("181716)")
' 181716'
>>> "{:0>8".format("181716)")
'00181716'
>>> "{:->8".format("181716)")
'--181716'
>>> "{:-<8".format("181716)")
'181716--'
>>> "{:-^8".format("181716)")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here --------------------'

浮動小数点の精度

f} 表示して浮動小数点のタイプを示し、その前に精度制御を追加することができます:

>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'

また、浮動小数点数にシンボルを指定することもできます:+ 表示する正の数の前に表示 +負の数の前に表示 -; (スペース)は正の数の前にスペースを追加し、負の数の前に -;- 何も追加しない({:f})の時と一致します:

>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'

指定された進数

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18)
'int: 18; hex: 12; oct: 22; bin: 10010'
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)
'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'

千位の区切り

千位の区切りとして "," を使用することができます:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

パーセンテージ表示

>>> "progress: {:.2%".format(19.88/22)
'progress: 90.36%'

実際には、formatはもっと多くのタイプシンボルをサポートしています:

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

他の技術

プレースホルダーのネスト

ある時はプレースホルダーのネストが非常に便利です:

>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')
'*****hello******'
>>>
>>> for num in range(5,12):
...  for base in "dXob":
...   print("{0:{width}{base}}".format(num, base=base, width=}}5), end=' ')
...  print()
...  
...
 5  5  5 101
 6  6  6 110
 7  7  7 111
 8  8 10 1000
 9  9 11 1001
 10  A 12 1010
 11  B 13 1011

関数として使用

フォーマット化パラメータを指定せずに、関数として呼び出すことができます:

>>> email_f = "Your email address was {email}".format
>>> print(email_f(email="[email protected]"))
Your email address was [email protected]

エスケープ大括号

文字列内で大括号を使用する必要がある場合、大括号をエスケープして使用できます:

>>> "{0} 集合は通常 {0} として表されます".format("empty")
「空集合は通常 {0} として表されます」

まとめ

これでこの記事のすべての内容が終わりました。本文の内容が皆様の学習や仕事に少しでも役立つことを願っています。疑問があれば、コメントを残してください。皆様の「呐喊教程」へのサポートに感謝します。

声明:本文の内容はインターネットから取得しており、著作権者に帰属します。インターネットユーザーにより自発的に提供されたコンテンツであり、本サイトは所有権を持ちません。また、人工編集は行われておらず、関連する法的責任も負いません。著作権侵害の疑いがある場合は、メールを送信してください:notice#oldtoolbag.com(メールを送信する際は、#を@に変更してください。申し訳ありませんが、関連する証拠を提供し、事実確認後、本サイトは即座に侵害疑いのコンテンツを削除します。

おすすめ