https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals

f-string

  • 기본형:

    • 문자열 앞에 f / F ; 중괄호 {표현식}에 변수나 계산식을 넣어 바로 치환.
  • 형식 지정자:

    • : 숫자 폭/정렬/소수점/진법/채움 문자 등을 제어.
      • “f{math.pi:.3f}” → 소수 3자리
      • “f{n:10d}” → 최소 폭 10, 정수.
  • 변환 플래그

    • ascii() !a
    • str() !s
    • repr() !r
  • 자기 설명 출력: f”{bugs=}” → bugs=‘roaches’처럼 식=값 형태로 보여줘 로깅/디버깅에 편리.

  • 컬럼 정렬 예: f”{name:10} {phone:10d}“처럼 폭을 맞춰 표 형태 출력.

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
    print(f'{name:10} ==> {phone:10d}')
 
# Sjoerd     ==>       4127
# Jack       ==>       4098
# Dcab       ==>       7678
 
print(f'My hovercraft is full of {animals!r}.')
# My hovercraft is full of 'eels'.
 
bugs = 'roaches'
count = 13
area = 'living room'
print(f'Debugging {bugs=} {count=} {area=}')
# Debugging bugs='roaches' count=13 area='living room'

← python 3.14으로