본문 바로가기
Research/Python

F-string에 대해

by RIEM 2021. 10. 18.
728x90

What is F-string?

In Python, there are many ways to format text strings. We know %-formatting, str.format() and string.Template. Inspite of advantages of those methods, there are still tricky points to use in practice. This is why we should use F-string.

 

How to use?

F-string is minimal and flexible. And f-string is an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with f, which contains expression inside braces. The expressions are replaced with their values.

import datetime
name = 'Mozart'
age = 31
birthday = datetime.date(1756,1,27)
print(f'My name is {name} and I\'m turning to {age+1}. You know my birthday is {birthday:%A, %B, %d, %Y}.')

> My name is Mozart and I'm turning to 32. You know my birthday is Tuesday, January, 27, 1756.

Let's compare F-string with other text string format and see how it is minimal.

value = 4 * 20
print('The value is {0}'.format(value))	#string.format()
print(f'The value is {value}') #f-string is more minimal, isn't it?

> The value is 80
> The value is 80

 

Reference

 

 

728x90

댓글