“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 |