0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】フォーマット済み文字列リテラル(f-strings)

Last updated at Posted at 2024-06-10

f-stringsは、Python 3.6から導入された新しい文字列フォーマット機能です。従来の % 演算子や str.format() メソッドに比べて、より簡潔で読みやすい表記ができます。
f-stringsを使うには、文字列リテラルの前に f または F を付けます。そして、{expression} の形式で値や式を埋め込むことができます。

name = 'Alice'
age = 25

# f-strings
print(f'My name is {name} and I am {age} years old.')
# 出力: My name is Alice and I am 25 years old.

式の評価結果が文字列に展開されるので、数値型や他のオブジェクトも直接埋め込めます。

x = 10
y = 3.14
print(f'The value of x is {x} and y is {y}')
# 出力: The value of x is 10 and y is 3.14

さらに、f-strings内で関数を呼び出したり、演算を行うこともできます。

import math

r = 5
print(f'The area of a circle with radius {r} is {math.pi * r**2}')  
# 出力: The area of a circle with radius 5 is 78.53981633974483

フォーマット指定子を使うことで、出力形式をきめ細かく制御できます。

x = 123.45678
print(f'Value of x is {x:,.2f}')  
# 出力: Value of x is 123.46

f-stringsは複数行にまたがる文字列にも対応しています。''' (三重引用符)を使えば改行を含めることができます。

msg = f'''
Hi {name}!
============
Your age is {age}
'''
print(msg)
# 出力:
# Hi Alice!
# ============
# Your age is 25

f-stringsは、可読性が高く、柔軟性に富んでいるため、モダンなPythonコードではよく使われる機能です。文字列フォーマットが必要な場面では、積極的にf-stringsを活用するとよいでしょう。

参考) 東京工業大学情報理工学院 Python早見表

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?