변수의 값을 유동적으로 문자열에 넣기 위한 몇가지 문자열 보간 방법이 있다.
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일
'Language > Python' 카테고리의 다른 글
파이썬 리스트 중복 요소 개수 찾기 (카운트) , 중복요소 제거하기 (0) | 2022.07.21 |
---|---|
논리연산자의 단축평가 (1) | 2022.07.19 |
파이썬 컨테이너 - 리스트, 튜플, 레인지, 세트, 딕셔너리 (1) | 2022.07.18 |
파이썬 예약어 keyword.kwlist (2) | 2022.07.18 |
파이썬 형 변환 (Typecasting - implicit, explicit) (1) | 2022.07.18 |