サーチ…


前書き

人間が見るためにデータを格納して変換するときには、文字列のフォーマットが非常に重要になります。 Pythonは、このトピックで概説されているさまざまな文字列書式設定メソッドを提供しています。

構文

  • "{}"。format(42)==> "42"
  • "{0}"。format(42)==> "42"
  • "{0:.2f}"。format(42)==> "42.00"
  • "{0:.0f}"。format(42.1234)==> "42"
  • "{答え}" format(no_answer = 41、answer = 42)==> "42"
  • "{答え:.2f}"。形式(no_answer = 41、回答= 42)==> "42.00"
  • "{[key]}"。format({'key': 'value'})==> "value"
  • "{[1]}"フォーマット(['zero'、 'one'、 'two'])==> "one"
  • "{回答} = {回答}"。書式(回答= 42)==> "42 = 42"
  • '' .join(['stack'、 'overflow'])==> "スタックオーバーフロー"

備考

  • PyFormat.infoをチェックして、それがどのように動作するかについての非常に徹底的で穏やかな紹介/説明を得てください。

文字列フォーマットの基本

foo = 1
bar = 'bar'
baz = 3.14

str.formatを使用して出力をフォーマットすることができます。ブラケットペアは、引数が渡された順序で引数に置き換えられます。

print('{}, {} and {}'.format(foo, bar, baz))
# Out: "1, bar and 3.14"

角括弧の中にインデックスを指定することもできます。数値はstr.format関数に渡される引数のインデックスに対応します(0ベース)。

print('{0}, {1}, {2}, and {1}'.format(foo, bar, baz))
# Out: "1, bar, 3.14, and bar"
print('{0}, {1}, {2}, and {3}'.format(foo, bar, baz))
# Out: index out of range error

名前付き引数も使用できます。

print("X value is: {x_val}. Y value is: {y_val}.".format(x_val=2, y_val=3))
# Out: "X value is: 2. Y value is: 3."

str.formatに渡すと、オブジェクトの属性を参照できます。

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('My value is: {0.value}'.format(my_value))  # "0" is optional
# Out: "My value is: 6"

辞書キーも同様に使用できます。

my_dict = {'key': 6, 'other_key': 7}
print("My other key is: {0[other_key]}".format(my_dict))  # "0" is optional
# Out: "My other key is: 7"

リストとタプルのインデックスにも同じことが適用されます:

my_list = ['zero', 'one', 'two']
print("2nd element is: {0[2]}".format(my_list))  # "0" is optional
# Out: "2nd element is: two"

注意: str.formatに加えて、Pythonは、 文字列の書式設定のために、 文字列の書式設定または補間演算子PEP 3101を参照)と呼ばれるモジュロ演算子% aloも提供しています。 str.format%後継str.formatあり、複数の置換を簡単に実行できるなど、柔軟性が向上します。

引数インデックスに加えて、中括弧の中に書式指定を含めることもできます。 (これは、特別ルールに従い、コロンに先行しなければならない表現です: )。書式指定の詳細については、 ドキュメントを参照してください。書式指定の例は、整列指示文:~^20^は中央整列を表し、合計幅は20、〜文字で埋めます):

'{:~^20}'.format('centered')
# Out: '~~~~~~centered~~~~~~'

formatは、引数の繰り返しなど、 %では不可能な動作を可能にします:

t = (12, 45, 22222, 103, 6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*t)    
# Out: 12 22222 45 22222 103 22222 6 22222

formatは関数なので、他の関数の引数として使うことができます:

number_list = [12,45,78]
print map('the number is {}'.format, number_list)
# Out: ['the number is 12', 'the number is 45', 'the number is 78']   
    

from datetime import datetime,timedelta
    
once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
delta = timedelta(days=13, hours=8,  minutes=20)
    
gen = (once_upon_a_time + x * delta for x in xrange(5))
    
print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))
#Out: 2010-07-01 12:00:00
#     2010-07-14 20:20:00
#     2010-07-28 04:40:00
#     2010-08-10 13:00:00
#     2010-08-23 21:20:00

アライメントとパディング

Python 2.x 2.6

format()メソッドを使用すると、文字列の配置を変更できます。 :[fill_char][align_operator][width]ここで、 align_operatorは次のいずれかのalign_operatorです。

  • <フィールドをwidth内で左揃えにします。
  • >フィールドをwidth内で右揃えにします。
  • ^フィールドはwidth内にセンタリングされwidth
  • =記号の後ろにパディングを配置するようにします(数値型のみ)。

fill_char (省略された場合、デフォルトは空白)は、パディングに使用される文字です。

'{:~<9s}, World'.format('Hello')
# 'Hello~~~~, World'

'{:~>9s}, World'.format('Hello')
# '~~~~Hello, World'

'{:~^9s}'.format('Hello')
# '~~Hello~~'

'{:0=6d}'.format(-123)
# '-00123'

注意:文字列関数ljust()rjust()center()zfill()を使用しても同じ結果が得られますが、これらの関数はバージョン2.5以降では推奨されていません。

書式リテラル(f-string)

リテラル形式の文字列は、 PEP 498 (Python3.6以降)で導入されました。文字列リテラルの先頭にfを付加して、現在のスコープ内のすべての変数を.formatに効果的に適用することができます。

>>> foo = 'bar'
>>> f'Foo is {foo}'
'Foo is bar'

これは、アラインメントやドット表記を含むより高度なフォーマット文字列でも機能します。

>>> f'{foo:^7s}'
'  bar  '

注: f''は、 bytes場合はb'' 、python2 u''場合はunicodeような特定の型を表しません。形成は直ちに適用され、通常の攪拌が行われる。

書式文字列はネストすることもできます。

>>> price = 478.23
>>> f"{f'${price:0.2f}':*>20s}"
'*************$478.23'

f-string内の式は、左から右の順に評価されます。これは、式に副作用がある場合にのみ検出可能です。

>>> def fn(l, incr):
...    result = l[0]
...    l[0] += incr
...    return result
...
>>> lst = [0]
>>> f'{fn(lst,2)} {fn(lst,3)}'
'0 2'
>>> f'{fn(lst,2)} {fn(lst,3)}'
'5 7'
>>> lst
[10]

datetimeによる文字列書式設定

どのクラスでも、 __format__メソッドを使用して独自の文字列書式構文を設定できます。これを手軽に利用できる標準のPythonライブラリの型はdatetime型で、 str.format内で直接strftimeような書式設定コードを使用できます:

>>> from datetime import datetime
>>> 'North America: {dt:%m/%d/%Y}.  ISO: {dt:%Y-%m-%d}.'.format(dt=datetime.now())
'North America: 07/21/2016.  ISO: 2016-07-21.'

公式ドキュメントには、日時フォーマッタの完全なリストがあります

GetitemとGetattrを使用したフォーマット

__getitem__をサポートするデータ構造体は、ネストされた構造体をフォーマットできます。

person = {'first': 'Arthur', 'last': 'Dent'} 
'{p[first]} {p[last]}'.format(p=person) 
# 'Arthur Dent'

オブジェクトの属性には、 getattr()を使用してアクセスできます。

class Person(object):
    first = 'Zaphod'
    last = 'Beeblebrox'

'{p.first} {p.last}'.format(p=Person())
# 'Zaphod Beeblebrox'

フロートフォーマット

>>> '{0:.0f}'.format(42.12345)
'42'

>>> '{0:.1f}'.format(42.12345)
'42.1'

>>> '{0:.3f}'.format(42.12345)
'42.123'

>>> '{0:.5f}'.format(42.12345)
'42.12345'

>>> '{0:.7f}'.format(42.12345)
'42.1234500'

参照の他の方法のための同じホールド:

>>> '{:.3f}'.format(42.12345)
'42.123'

>>> '{answer:.3f}'.format(answer=42.12345)
'42.123'

浮動小数点数は、 科学的表記法またはパーセントで書式設定することもできます。

>>> '{0:.3e}'.format(42.12345)
'4.212e+01'

>>> '{0:.0%}'.format(42.12345)
'4212%'

{0}{name}表記を組み合わせることもできます。これは、すべての変数を1つの宣言であらかじめ指定された小数点以下に丸める場合に特に便利です。

>>> s = 'Hello'
>>> a, b, c = 1.12345, 2.34567, 34.5678
>>> digits = 2

>>> '{0}! {1:.{n}f}, {2:.{n}f}, {3:.{n}f}'.format(s, a, b, c, n=digits)
'Hello! 1.12, 2.35, 34.57'

数値の書式設定

.format()メソッドは、次のような異なるフォーマットの数値を解釈できます。

>>> '{:c}'.format(65)    # Unicode character
'A'

>>> '{:d}'.format(0x0a)  # base 10
'10'

>>> '{:n}'.format(0x0a)  # base 10 using current locale for separators
'10'

整数を異なるベース(16進数、8進数、2進数)にフォーマットする

>>> '{0:x}'.format(10) # base 16, lowercase - Hexadecimal
'a'

>>> '{0:X}'.format(10) # base 16, uppercase - Hexadecimal
'A'

>>> '{:o}'.format(10) # base 8 - Octal
'12'

>>> '{:b}'.format(10) # base 2 - Binary
'1010'

>>> '{0:#b}, {0:#o}, {0:#x}'.format(42) # With prefix
'0b101010, 0o52, 0x2a'

>>> '8 bit: {0:08b}; Three bytes: {0:06x}'.format(42) # Add zero padding
'8 bit: 00101010; Three bytes: 00002a'

書式設定を使用して、RGBフロートタプルをカラーの16進文字列に変換します。

>>> r, g, b = (1.0, 0.4, 0.0)
>>> '#{:02X}{:02X}{:02X}'.format(int(255 * r), int(255 * g), int(255 * b))
'#FF6600'

整数だけを変換することができます:

>>> '{:x}'.format(42.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'x' for object of type 'float'

クラスのカスタム書式設定

注意:

以下のすべてはstr.formatメソッドとformat関数に適用されます。以下のテキストでは、2つは同じ意味です。

format関数に渡されるすべての値に対して、Pythonはその引数に対して__format__メソッドを探します。したがって、独自のカスタムクラスで独自の__format__メソッドを使用して、 format関数がクラスとその属性をどのように表示およびフォーマットするかを決定することができます。

これは、より異なる__str__のように、方法__format__アカウントに合わせ、フィールド幅などを含むフォーマット言語を取る、とさえ(必要であれば)、独自の書式指定子を実装し、独自の書式設定の言語拡張することができます方法。 1

object.__format__(self, format_spec)

例えば ​​:

# Example in Python 2 - but can be easily applied to Python 3

class Example(object):
    def __init__(self,a,b,c):
        self.a, self.b, self.c = a,b,c

    def __format__(self, format_spec):
        """ Implement special semantics for the 's' format specifier """
        # Reject anything that isn't an s
        if format_spec[-1] != 's':
            raise ValueError('{} format specifier not understood for this object', format_spec[:-1])

        # Output in this example will be (<a>,<b>,<c>)
        raw = "(" + ",".join([str(self.a), str(self.b), str(self.c)]) + ")"
        # Honor the format language by using the inbuilt string format
        # Since we know the original format_spec ends in an 's' 
        # we can take advantage of the str.format method with a 
        # string argument we constructed above
        return "{r:{f}}".format( r=raw, f=format_spec )

inst = Example(1,2,3)
print "{0:>20s}".format( inst )
# out :              (1,2,3)
# Note how the right align and field width of 20 has been honored.

注意:

カスタムクラスにカスタム__format__メソッドがなく、クラスのインスタンスがformat関数に渡された場合、 Python2__str__メソッドまたは__repr__メソッドの戻り値を使用して何を出力するかを決定します。デフォルトのreprが使用されます)、フォーマットするにはsフォーマット指定子を使用する必要があります。 Python3では、カスタムクラスをformat関数に渡すには、カスタムクラスで__format__メソッドを定義する必要があります。

ネストされた書式設定

一部の形式では、書式設定された文字列の幅や配置など、追加のパラメータを使用できます。

>>> '{:.>10}'.format('foo')
'.......foo'

それらはまた、パラメータとして提供することができるformatよりネストによって{}内部を{}

>>> '{:.>{}}'.format('foo', 10)
'.......foo'
'{:{}{}{}}'.format('foo', '*', '^', 15)
'******foo******'

後者の例では、書式文字列'{:{}{}{}}''{:*^15}'変更されています実際の文字列'foo'はそのようにフォーマットされます。

これは、表形式のデータを整列する際に、事前にパラメータがわからない場合に役立ちます。

>>> data = ["a", "bbbbbbb", "ccc"]
>>> m = max(map(len, data))
>>> for d in data:
...     print('{:>{}}'.format(d, m))
      a
bbbbbbb
    ccc

文字列のパディングとトランケート、組み合わせ

変数を3文字の列に出力したいとします。

注:倍増{}はそれらをエスケープします。

s = """

pad
{{:3}}             :{a:3}:

truncate
{{:.3}}            :{e:.3}:

combined
{{:>3.3}}          :{a:>3.3}:
{{:3.3}}           :{a:3.3}:
{{:3.3}}           :{c:3.3}:
{{:3.3}}           :{e:3.3}:
"""

print (s.format(a="1"*1, c="3"*3, e="5"*5))

出力:

pad
{:3}             :1  :

truncate
{:.3}            :555:

combined
{:>3.3}          :  1:
{:3.3}           :1  :
{:3.3}           :333:
{:3.3}           :555:

名前付きプレースホルダ

書式文字列には、書式設定のためにキーワード引数を使用して補間された名前付きプレースホルダが含まれformat

辞書を使う(Python 2.x)

>>> data = {'first': 'Hodor', 'last': 'Hodor!'}
>>> '{first} {last}'.format(**data)
'Hodor Hodor!'

辞書を使う(Python 3.2以降)

>>> '{first} {last}'.format_map(data)
'Hodor Hodor!'

str.format_mapを使用すると、辞書を最初に解凍しなくても辞書を使用できます。また、 dataのクラス(カスタムタイプかもしれない)が、新しく埋め込まれたdict代わりに使用されます。

辞書なし:

>>> '{first} {last}'.format(first='Hodor', last='Hodor!')
'Hodor Hodor!'


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow