Pythonのf文字列(またはフォーマット文字列)は、文字列内に変数の値を直接埋め込む機能です。文字列の前に f
または F
を置き、文字列内で変数を波括弧 {}
で囲むことで使用できます。
Pythonのf文字列の基本的な使い方
以下に、Pythonのf文字列の基本的な使い方を示します。
name = 'Eric'
print(f'Hello, my name is {name}') # 'Hello, my name is Eric'
number = 7
print(f'My lucky number is {number}') # 'My lucky number is 7'
price = 19.99
print(f'The price of this book is {price}') # 'The price of this book is 19.99'
このように、f文字列を使用すると、文字列内に変数の値を直接埋め込むことができます。
f文字列の使用例
f文字列は、リストや関数の結果など、さまざまなデータ型の値を文字列に埋め込むことができます。
py = "PythonCarnival"
print(f'これからも {py}をよろしくお願いします! ') # 'これからもPythonCarnivalをよろしくお願いします! '
x = [1, 2, 3, 4, 5]
print(f' {x}') # ' [1, 2, 3, 4, 5]'
def foo(x:int) -> int:
return x + 1
print(f' {foo (0)}') # '1'
このように、f文字列はPythonのコードをより直感的で簡潔に書くための強力なツールです。.