Python
Python - 왜 f-string을 쓰라는 걸까 "Formatting a regular string which could be a f-string"
올엠
2024. 3. 25. 17:12
반응형
Vusual Studio Code를 작성하다보면 기존 format 습관에 다음과 같은 경고문구를 자주 접하게 된다.

Formatting a regular string which could be a f-string
필자도 본 경고가 눈에 띄어서 찾아본 결과 Python 3.6 버전부터 만들어진 새로운 문자열 작성 방법으로 f-string 사용을 권장하는 것이다.
이유는 보다 간결히 작성이 가능하다는 것.
그리고 코드 실행상의 성능 이점도 있다고 한다. 다만 %-formatting 이 가장 속도상 이점이 있지만, 기존 format 을 사용하는 방식보다 속도 개선과 코드 가독성이 좋은 f-string이 가장 효율적일 것으로 판단된다.
%-formatting
>>> timeit.timeit("""test = "timeit"
... one = 1
... two = 2
... three = 3
... str_format = '%s is %s %s %s' % (test, one, two, three)""", number=1000000)
0.16582620795816183
format
>>> timeit.timeit("""test = "timeit"
... one = 1
... two = 2
... three = 3
... str_format = '{} is {} {} {}'.format(test, one, two, three)""", number=1000000)
0.2097106670262292
f-string
>>> timeit.timeit("""test = "timeit"
... one = 1
... two = 2
... three = 3
... str_format = f'{test} is {one} {two} {three}'""", number=1000000)
0.1873102909885347
위 테스트 결과를 보면 f-string은 format 보다 빠르면서 가독성이 좋은 것을 알 수 있다.
이러한 이유로, f-string을 앞으로 사용해 보는게 어떨까?
# format를 사용할 경우 코드 길이
simple = {'test':'testvalue'}
str_format = '{}'.format(simple['test'])
# f-string를 사용할 경우 코드 길이
str_format = f"{simple['test']}"
반응형