본문 바로가기
커리어 connecting the dots

파이썬 기본 - print 문법과 format 메소드란 (2-1강 필기)

by 김꾸꾸 2021. 12. 15.
728x90

print

출력. 디버깅 시 사용하기도 한다. 기본이 됨.

 

#기본print

print('Python Start') = print("Python Start") = print('''Python Start''') ...

 

#separator 옵션

print('L','O','V','E', sep='') 

-> LOVE

print('L','O','V',E', sep=' ')

-> L O V E

등 콤마로 하나하나를 연결할 때 뒤에 붙는 separator에 따라 달라지게 할 수 있다.

 

print('010','1234','5678', sep='-')

-> 010-1234-5678

 

#end 옵션

print 문에 end 옵션이 들어가면 뒤 옵션 다음으로 다음 줄을 이어준다
문장마다 엔터를 너무 많이 쳐서 한 눈에 볼 수 없을 때 사용하는 옵션

 

print('Welcome to', end=' ')

print('Seventeen', end=' ')

print('Studio')

-> Welcome to Seventeen Studio

 

# file 옵션

import sys
print('Learn Python', file=sys.stdout)

ㄴ 근데 이게 뭔지는 아직 안 배웠다...흠

 

 

# format method 사용 (d: 정수, s: 문자, f: 소수점)

format method는 해당 함수 안에 오는 내용을 {} 브라켓, 플레이스홀더에 맞는 형식으로 변환시킬 수 있다.

 

 

#s #문자열 #생략가능

1) 기본 출력

print('%s %s' % ('one', 'two'))
print('{} {}'.format('one', 'two'))
 -->one two
print('{1} {0}'.format('one', 'two'))
 -->two one
 -->숫자열은 0123456789 순서대로 진행되어서, 순서를 바꿔서 입력하라는 뜻이 되기 때문에

2) 왼쪽 오른쪽으로 글자를 떼어봅시다.

print('%10s' % ('nice'))
=      nice
print('{:>10}.format('nice'))
=      nice
print{'{:@>10}'.format('nice'))
=@@@@@@nice
print('%-10s' % ('nice'))
=nice
print('{:10}.format('nice'))
=nice
print('{:^10}.format('nice'))
=   nice   (중앙정렬)

3) 절삭해봅시다

print('%.5s' % ('nice'))
=nice
print('%.5s' % ('Seventeen'))
=Seven
=5자리 확보했으니, 거기서 잘라라
print('%5s' % ('Seventeen'))
=Seventeen
=5자리 확보했고, 그 이상이면 다 출력해라

 

 

#d #정수 #format method에서도 생략불가

print('%d %d' % '(1,2)'
=1 2
print({}  {}.format(1,2))
=1  2

print('%4d' % (42))
=  42
print('{:4d}.format(42))
=  42
 # d에서는 :> 안해도 오른쪽으로 붙음

 

#f #소수점 #format method에서도 생략 불가

print('%f' % (3.141592653589793))
=적당히 끊어서 내보내라
=3.141593

print('%1.3f' % (3.141592653589793)
=총 자리 최소 1개, 소숫점은 3개까지만
=3.142
 
print('%7.2f' % (3.141592653589793)
=총 자리 최소 7개, 소수점아래 2개만
=   3.14

print('{:f}'.format(3.141592653589793))
=3행

print('{:06.2f}'.format(3.141592653589793))
=총 자리 최소 6개, 소수점아래 2개만, 앞은 0으로 채워라.
=003.14

 

사실상 가장 잘 정리된 자료는

https://www.w3schools.com/python/ref_string_format.asp

 

Python String format() Method

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

728x90

댓글