Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python f-string(형식화된 문자열 리터럴) 완벽 정리: 기본 문법부터 람다 활용까지

파이썬(Python)은 문자열을 손쉽게 포맷할 수 있는 새로운 방식인 f-string(형식화된 문자열 리터럴)을 제공합니다. 이 기능은 PEP 498 제안에 따라 Python 3.6부터 도입되었습니다. 문자열 앞에 접두사 'f'를 붙여서 사용한다고 해서 f-string이라고 부르며, 이 접두사는 해당 문자열이 포맷팅 용도로 사용될 수 있음을 나타냅니다.

f-string은 중괄호 {} 안에 변수나 표현식을 그대로 작성할 수 있어, 기존의 % 포맷팅이나 str.format() 메서드보다 훨씬 간결하고 가독성이 뛰어납니다.

아래 예제들을 통해 f-string의 다양한 활용법을 하나씩 살펴보겠습니다.

예제 1: 기본 사용법

name = 'Rajesh'
age = 13 * 3
fString = f'My name is {name} and my age is {age}'
print(fString)
# 대문자 'F'를 사용해도 동일하게 동작합니다.
print(F'My name is {name} and my age is {age}')
# fString은 이미 값이 평가된 상태이므로,
# 이후 변수 값을 변경해도 fString의 값은 달라지지 않습니다.
name = 'Zack'
age = 44
print(fString)

출력 결과

My name is Rajesh and my age is 39
My name is Rajesh and my age is 39
My name is Rajesh and my age is 39

예제 2: 표현식과 변환(conversion) 활용

f-string 안에서는 단순 변수 치환을 넘어 산술 연산, !r 같은 변환 지정자, 날짜 포맷 지정까지 자유롭게 사용할 수 있습니다.

from datetime import datetime

name = 'Rajesh'
age = 13 * 3
dt = datetime.now()
print(f' Age after ten years will be {age + 10}')
print(f'Name with quotes = {name!r}')
print(f'Default formatted Date = {dt}')
print(f'Modified Date format = {dt: %d/%m/%Y}')

출력 결과

Age after ten years will be 49
Name with quotes = 'Rajesh'
Default formatted Date = 2019-02-11 14:52:05.307841
Modified Date format = 11/02/2019

예제 3: 객체와 속성 접근

중괄호 안에서 객체의 속성(attribute)에도 점(.) 표기법으로 바로 접근할 수 있습니다.

class Vehicle:
    Model = 0
    Brand = ''

    def __init__(self, Model, Brand):
        self.Model = Model
        self.Brand = Brand

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

Car = Vehicle(2018, 'Maruti')
print(Car)
print(f'Vehicle: {Car}\nModel is {Car.Model} and Brand is {Car.Brand}')

출력 결과

E[Model=2018, Brand=Maruti]
Vehicle: E[Model=2018, Brand=Maruti]
Model is 2018 and Brand is Maruti

예제 4: 함수 호출

f-string 내부에서는 함수를 직접 호출하고 그 반환값을 문자열에 삽입할 수도 있습니다.

def Multiply(x, y):
    return x * y

print(f'Multiply(40,20) = {Multiply(40, 20)}')

출력 결과

Multiply(40,20) = 800

예제 5: 람다(lambda) 표현식

람다 표현식을 f-string 안에서 즉시 실행하여 간단한 계산 결과를 바로 출력할 수도 있습니다.

x = -40.9
print(f'Lambda absolute of (-40.9) is : {(lambda x: abs(x))(x)}')
print(f'Lambda Square of 2^4 is: {(lambda x: pow(x, 2))(4)}')

출력 결과

Lambda absolute of (-40.9) is : 40.9
Lambda Square of 24 is: 16

이처럼 f-string은 변수 치환, 표현식 평가, 날짜 포맷팅, 객체 속성 접근, 함수 호출, 람다 실행까지 폭넓게 지원합니다. 코드가 짧아지고 읽기 쉬워지므로, Python 3.6 이상 환경이라면 문자열 포맷팅 시 f-string을 적극적으로 활용하는 것이 좋습니다.