Python f-strings(PEP 498)- リテラル文字列補完

Python 3.6で導入されたPEP-498の下、Pythonのf-stringsまたはフォーマット済みの文字列は、文字列をフォーマットする新しい方法です。これはまた、リテラル文字列内挿とも呼ばれています。

なぜf文字列が必要なのですか? (Naze f-moji retsu ga hitsuyōna no desu ka?)

Pythonは文字列のフォーマットに様々な方法を提供しています。それらを簡単に見て、それらが抱える問題についても見てみましょう。

  • % formatting – great for simple formatting but limited support for strings, ints, doubles only. We can’t use it with objects.
  • Template Strings – it’s very basic. Template strings work with keyword arguments like dictionary only. We are not allowed to call any function and arguments must be strings.
  • String format() – Python String format() function was introduced to overcome the issues and limited features of %-formatting and template strings. However, it’s too verbose. Let’s look at its verbosity with a simple example.
    >>> age = 4 * 10
    >>> ‘My age is {age}.’.format(age=age)
    ‘My age is 40.’

Pythonのf文字列は、format()関数とほぼ同じように機能しますが、format()関数にある冗長さをすべて取り除いています。では、上記の文字列をf文字列を使って簡単に書式設定する方法を見てみましょう。

>>> f'My age is {age}'
'My age is 40.'

Pythonのf-stringsは、文字列のフォーマットに最小限の構文を導入するために使用されます。これらの式は実行時に評価されます。Pythonのバージョン3.6以上を使用している場合、すべての文字列のフォーマット要件にf-stringsを使用するべきです。

Pythonのf-stringsの例

f-stringsの簡単な例を見てみましょう。

name = 'Pankaj'
age = 34

f_string = f'My Name is {name} and my age is {age}'

print(f_string)
print(F'My Name is {name} and my age is {age}')  # f and F are same

name = 'David'
age = 40

# f_string is already evaluated and won't change now
print(f_string)

結果:

My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34

Pythonは文を1つずつ実行し、f文字列式が評価されると、式の値が変更されても変わらない。したがって、上記のコードスニペットでは、プログラムの後半で ‘name’ と ‘age’ 変数が変更されても、f_stringの値は変わらない。

1. 式と変換を使用したf-strings

日本語で以下を言い換えると、ただ一つのオプションで構いません:
f-stringsを使用すると、datetimeを特定の形式に変換することができます。また、f-strings内で数式を実行することも可能です。

from datetime import datetime

name = 'David'
age = 40
d = datetime.now()

print(f'Age after five years will be {age+5}')  # age = 40
print(f'Name with quotes = {name!r}')  # name = David
print(f'Default Formatted Date = {d}')
print(f'Custom Formatted Date = {d:%m/%d/%Y}')

出力:

Age after five years will be 45
Name with quotes = 'David'
Default Formatted Date = 2018-10-10 11:47:12.818831
Custom Formatted Date = 10/10/2018

2. f-stringsは生の文字列をサポートしています。

私達は、f-文字列を使って生の文字列を作成することもできます。

print(f'Default Formatted Date:\n{d}')
print(fr'Default Formatted Date:\n {d}')

出力:

Default Formatted Date:
2018-10-10 11:47:12.818831
Default Formatted Date:\n 2018-10-10 11:47:12.818831

3. オブジェクトと属性を持つf-strings。

f-stringsではオブジェクト属性にもアクセスすることができます。

class Employee:
    id = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n

    def __str__(self):
        return f'E[id={self.id}, name={self.name}]'


emp = Employee(10, 'Pankaj')
print(emp)

print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')

結果:

E[id=10, name=Pankaj]
Employee: E[id=10, name=Pankaj]
Name is Pankaj and id is 10

4. 関数を呼び出すf-strings

我々はf-stringsのフォーマットにおいても関数を呼び出すことができます。

def add(x, y):
    return x + y


print(f'Sum(10,20) = {add(10, 20)}')

出力:Sum(10,20) = 30

5. 空白を含んだf文字列

もし式の前後に空白があれば、無視されます。文字列の一部に空白が含まれている場合は、保持されます。

>>> age = 4 * 20
>>> f'   Age = {  age   }  '
'   Age = 80  '

6. f-stringsを用いたLambda式

私たちはf-string式の中でも、ラムダ式を使うことができます。

x = -20.45
print(f'Lambda Example: {(lambda x: abs(x)) (x)}')

print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')

出力:

Lambda Example: 20.45
Lambda Square Example: 25

7. f-stringsのその他の例

Pythonのf文字列のいくつかのさまざまな例を見てみましょう。

print(f'{"quoted string"}')
print(f'{{ {4*10} }}')
print(f'{{{4*10}}}')

出力:

quoted string
{ 40 }
{40}

それがPythonフォーマット済み文字列、またはf-stringsについてのすべてです。

弊社のGitHubリポジトリから、完全なPythonスクリプトやその他のPythonの例をチェックアウトすることができます。

参照:PEP-498、公式ドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *