728x90
반응형
“Formatted String Literals.”
1) f-string nested in nested
python 버전이 올라가면서 다양하고 편리한 기능이 많이 생겼다. 그 중하나인 f-string 안에 다시 f-string을 사용하는 것이다. 이렇게 되면 앞서 소개한 f-string trick(1)의 datetime을 자유자재로 사용할 수 있다.
from datetime import datetime
now : datetime = datetime.now()
date_spec : str = "%d.%m.%Y"
date = now | date_spec
print(f"{now:{date_spec}}")
# '17.03.2024'
2) file path
file path를 문자열로 처리할 때 escape 문자 '/'가 포함되어 Error가 나는 경우가 많다.
custom_folder : str="test"
path : str = f"\Users\{custom_folder}\Desktop"
위 코드를 실행시키면 "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \UXXXXXXXX escape" 구문 오류가 난다.
이전에는 f-string을 사용하면 r(raw-string)을 사용할 수 없어 os.path를 사용해 join을 하거나 r-string을 사용해야 했다. 하지만 지금은 fr""(f-string + r-string) 한꺼번에 사용이 가능하다.
custom_folder : str="test"
path : str = fr"\Users\{custom_folder}\Desktop"
# '\\Users\\test\\Desktop'
3) 문자열 출력 Conversation 사용하기 (!s !a !r)
If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls str() on the result, '!r' calls repr(), and '!a' calls ascii().
python 3.8부터 conversation 기능으로 문자열을 custom 하게 출력할 수 있다.
# !s
print(f"{name!s} was born on {birth!s} who likes {banana!s}")
# monkey was born on 2024-03-17 who likes 🍌
# !r
print(f"{name!r} was born on {birth!r} who likes {banana!r}")
# 'monkey' was born on datetime.date(2024, 3, 17) who likes '🍌'
# !a
print(f"{name!a} was born on {birth!a} who likes {banana!a}")
# 'monkey' was born on datetime.date(2024, 3, 17) who likes '\U0001f34c'
반응형
'Python' 카테고리의 다른 글
[site-packages] AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK' (0) | 2024.06.01 |
---|---|
string method. 1~20 (0) | 2024.04.28 |
[Python] 이거 모르면 너는 초보 (0) | 2024.03.05 |
[Python] f-string trick (1) (0) | 2024.03.02 |
FastAPI - starlette.routing.NoMatchFound: No route exists for name (0) | 2024.01.19 |