Python f-strings は思った以上のことができます


この記事では、f-strings と、f-strings でできるいくつかのクールなことについて話します.そのため、ほとんどの人はすでに f 文字列とは何かを知っているでしょう.

🎯 f-strings



「フォーマットされた文字列リテラル」とも呼ばれる f-string は、先頭に f があり、値に置き換えられる式を含む中括弧を持つ文字列リテラルです.

1.後ろに「=」を入れる



あなたができる本当にクールなことの 1 つは、単に等号を後ろに置くことです.

コード -




word = 'Hello World'
num = 152
print(f'The value of word is f{word}')
print(f'{word=}')

print(f'The value of num is f{num}')
print(f'{num=}')
print(f'{num + 8 =}')


出力 -




The value of word is Hello World
word='Hello World'
The value of num is f152
num=152
num + 8 =160



2.コンバージョン



したがって、気づいていない場合は、 式の後の f 文字列の中括弧内に

```!a ,!s , !r ```

、 と
これらが行うことは、このことの値を出力する代わりに、それに加えて追加のことを行います.



!r - repr() 'repr() メソッドは、オブジェクトの印刷可能な表現を含む文字列を返します.'

!a - ascii 'ASCII 以外のすべての文字は、ASCII で安全にエスケープされたバージョンに置き換えられます'


!s - 文字列変換演算子「フォーマット」

コード -




def conversion():
    str_value = "Hello World 😀"
    print(f'{str_value!r}')
    print(f'{str_value!a}')
    print(f'{str_value!s}')

conversion()



出力 -




'Hello World 😀'
'Hello World \U0001f600'
Hello World 😀


3.フォーマット



変数の後の「:」

コード -




import datetime

def formatting():
    num_value = 475.2486
    now = datetime.datetime.utcnow()

    #Formats the datee in the given format
    print(f'{now=:%Y-%m-%d}')

    # Rounds the decimal to 2 digits
    print(f'{num_value:.2f}')

formatting()


出力 -




now=2021-08-04
475.25