python
Python: f-String (Literal String Interpolation)
iosroid
2020. 4. 28. 18:23
python 3.6 이후에는 f-String 을 쓰면 좋다.
이전엔
% format
>>> world = "world"
>>> "Hi, %s!" % world
'Hi, world!'
>>> new = "new"
>>> "Hi, %s %s!" % (new, world)
'Hi, new world!'
문자열과 변수가 따로 놀아 한눈에 안들어온다. 변수가 많아지면 더 복잡해진다.
str.format()
>>> "Hi, {} {}".format(new, world)
'Hi, new world'
>>> "Hi, {1} {0}".format(new, world)
'Hi, world new'
여전히 따로 놀아서 보기 어렵다.
>>> "Hi, {string1} {string2}".format(string1=new, string2=world)
'Hi, new world'
문자열을 쓰면 조금 나아진다. 하지만 뒤 처리가 지저분 하다.
이 보다 간단하게 쓸 수 있는게 f-string 이다.
f-Strings
PEP 498 - Literal String Interpolation
f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
>>> f"Hi, {new} {world}"
'Hi, new world'
문자열에 f
를 붙이는 수고만 더하면 format()
, % ()
을 날려버릴 수 있다.
>>> def foo():
... return 20
...
>>> f"result={foo()}"
'result=20'
>>> f"{10*2+66}"
'86'
>>> "Hi! " + f"{new} " + f"{world}"
'Hi! new world'