Language/Python
파이썬 String Interpolation (문자열 보간) - %, format, f-strings
지나온
2022. 7. 19. 10:08
변수의 값을 유동적으로 문자열에 넣기 위한 몇가지 문자열 보간 방법이 있다.
num=int(input())
print('번호:{}'.format(num))
print('번호:%d' %num)
print(f'번호:{num}')
입력받은 숫자 num에 대해 번호:num 형식으로 출력되도록 하였다.
%-formatting
%s : 문자열 str
%d : 정수 int
%f : 실수 float
w='world'
print('hello %s' % w) #hello world
str.format()
w='world'
n=2022
print('hello {},{}'.format(w,n))
f-strings
w='world'
n=2022
print(f'hello {w}, {n}')
실수 표기
pi=3.141592
print(f'원주율={pi:.3}') #원주율=3.14
.3으로 소수점 3자리에서 반올림하여 두자리만 표시되도록 한다.
날짜 표기
datetime을 import하여 현재 날짜를 가지고 올수있고 출력 형식을 바꿀 수 있다.
import datetime
today = datetime.datetime.now()
print(today) #2022-07-19 10:06:40.647563
print(f'{today:%y}년 {today:%m}월 {today:%d}일') #22년 07월 19일