파이썬, f 문자열 기초와 활용 예제 

 

from datetime import datetime

now: datetime = datetime.now()

print(now)  # 2025-01-18 21:16:59.704027
print(f'{now:%y.%m.%d}')  # 25.01.18
print(f'{now:%Y.%m.%d}')  # 2025.01.18
print(f'{now:%D}')        # 01/18/25
print(f'{now:%H:%M:%S}')  # 21:20:48
print(f'{now:%c}')        # Sat Jan 18 21:21:55 2025
print(f'{now:%I %p}')     # 09 PM

n: int = 1000000000

print(f'{n:_}')  #1_000_000_000
print(f'{n:,}')  #1,000,000,000

n: float = 1234.567890123

print(n)            # 1234.567890123
print(round(n, 2))  # 1234.57
print(f'{n:.2f}')   # 1234.57
print(f'{n:.0f}')   # 1235
print(f'{n:,.3f}')  # 1,234.568
print(f'{n:_.3f}')  # 1_234.568

v: str = 'var'

print(f'{v:>20}:')  #                 var:
print(f'{v:<20}:')  #var                 :
print(f'{v:_>20}:') #_________________var:
print(f'{v:*<20}:') #var*****************:
print(f'{v:|^20}:') #||||||||var|||||||||:

a: int = 10
b: int = 5

print(f'a + b = {a+b}') # a + b = 15
print(f'{a + b = }')    # a + b = 15
print(f'{a+b=}')        # a+b=15

print(f'{bool(a) = }')  # bool(a) = True

v: str = 'Hello, world!'
print(f'{v = }')        # v = 'Hello, world!'

 

[실행 결과] 

2025-01-18 21:33:43.260997
25.01.18
2025.01.18
01/18/25
21:33:43
Sat Jan 18 21:33:43 2025
09 PM
1_000_000_000
1,000,000,000
1234.567890123
1234.57
1234.57
1235
1,234.568
1_234.568
                 var:
var                 :
_________________var:
var*****************:
||||||||var|||||||||:
a + b = 15
a + b = 15
a+b=15
bool(a) = True
v = 'Hello, world!'

 

반응형

+ Recent posts