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'
๋ฐ˜์‘ํ˜•
๋‹คํ–ˆ๋‹ค