웹사이트 검색

Python f-문자열 - PEP 498 - 리터럴 문자열 보간


Python f-문자열 또는 서식이 지정된 문자열은 문자열 서식을 지정하는 새로운 방법입니다. 이 기능은 PEP-498의 Python 3.6에서 도입되었습니다. 리터럴 문자열 보간이라고도 합니다.

f-스트링이 필요한 이유는 무엇입니까?

Python은 문자열을 형식화하는 다양한 방법을 제공합니다. 그들과 그들이 가진 문제가 무엇인지 빠르게 살펴 보겠습니다.

  • % formatting - great for simple formatting but limited support for strings, ints, doubles only. We can’t use it with objects.

  • Template Strings - it’s very basic. function and arguments must be strings.

  • String format() - Python String format() function was introduced to overcome the issues and limited features of %-formatting and template strings. However, it’s too verbose. Let’s look at its verbosity with a simple example.

    >>> age = 4 * 10
    >>> 'My age is {age}.'.format(age=age)
    'My age is 40.'
    

Python f-strings는 format() 함수와 거의 유사하게 작동하지만 format() 함수가 가지고 있는 모든 장황함을 제거합니다. f-문자열을 사용하여 위의 문자열을 얼마나 쉽게 형식화할 수 있는지 봅시다.

>>> f'My age is {age}'
'My age is 40.'

Python f-strings는 문자열 형식화를 위한 최소 구문을 갖도록 도입되었습니다. 표현식은 런타임에 평가됩니다. Python 3.6 이상 버전을 사용하는 경우 모든 문자열 형식 요구 사항에 대해 f-문자열을 사용해야 합니다.

Python f-문자열 예제

f-스트링의 간단한 예를 살펴보겠습니다.

name = 'Pankaj'
age = 34

f_string = f'My Name is {name} and my age is {age}'

print(f_string)
print(F'My Name is {name} and my age is {age}')  # f and F are same

name = 'David'
age = 40

# f_string is already evaluated and won't change now
print(f_string)

산출:

My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34

Python은 명령문을 하나씩 실행하며 f-string 표현식이 평가되면 표현식 값이 변경되더라도 변경되지 않습니다. 그래서 위의 코드 스니펫에서 프로그램 후반부에 '이름'과 '나이' 변수가 변경된 후에도 f_string 값이 그대로 유지됩니다.

1. 표현식과 변환이 있는 f-문자열

f-문자열을 사용하여 datetime을 특정 형식으로 변환할 수 있습니다. f-문자열에서 수학 표현식을 실행할 수도 있습니다.

from datetime import datetime

name = 'David'
age = 40
d = datetime.now()

print(f'Age after five years will be {age+5}')  # age = 40
print(f'Name with quotes = {name!r}')  # name = David
print(f'Default Formatted Date = {d}')
print(f'Custom Formatted Date = {d:%m/%d/%Y}')

산출:

Age after five years will be 45
Name with quotes = 'David'
Default Formatted Date = 2018-10-10 11:47:12.818831
Custom Formatted Date = 10/10/2018

2. f-문자열은 원시 문자열을 지원합니다.

f-문자열을 사용하여 원시 문자열도 만들 수 있습니다.

print(f'Default Formatted Date:\n{d}')
print(fr'Default Formatted Date:\n {d}')

산출:

Default Formatted Date:
2018-10-10 11:47:12.818831
Default Formatted Date:\n 2018-10-10 11:47:12.818831

3. 객체와 속성이 있는 f-문자열

우리는 f-strings에서도 객체 속성에 접근할 수 있습니다.

class Employee:
    id = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n

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


emp = Employee(10, 'Pankaj')
print(emp)

print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')

산출:

E[id=10, name=Pankaj]
Employee: E[id=10, name=Pankaj]
Name is Pankaj and id is 10

4. 함수를 호출하는 f-문자열

f-문자열 형식으로 함수를 호출할 수도 있습니다.

def add(x, y):
    return x + y


print(f'Sum(10,20) = {add(10, 20)}')

출력: Sum(10,20)=30

5. 공백이 있는 f-문자열

식에 선행 또는 후행 공백이 있으면 무시됩니다. 리터럴 문자열 부분에 공백이 포함되어 있으면 그대로 유지됩니다.

>>> age = 4 * 20
>>> f'   Age = {  age   }  '
'   Age = 80  '

6. f-문자열을 사용한 람다 식

f-string 표현식 내부에서도 람다 표현식을 사용할 수 있습니다.

x = -20.45
print(f'Lambda Example: {(lambda x: abs(x)) (x)}')

print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')

산출:

Lambda Example: 20.45
Lambda Square Example: 25

7. f-strings 기타 예제

Python f-strings의 몇 가지 기타 예를 살펴보겠습니다.

print(f'{"quoted string"}')
print(f'{{ {4*10} }}')
print(f'{{{4*10}}}')

산출:

quoted string
{ 40 }
{40}

이것이 f-문자열이라고도 하는 파이썬 형식의 문자열에 대한 전부입니다.

GitHub 리포지토리에서 전체 Python 스크립트와 더 많은 Python 예제를 확인할 수 있습니다.

참조: 공식 문서