강의노트 print() 함수

조회수 1527 • 댓글 0 • 수정 2주 전 크게 보기  
  • 개요
  • 파이썬 개요

주석

  • 코멘트 문
# 주석
''' 여러 줄 주석
일 경우 '''

연결

  • 긴 행인 경우 행 끝에 \를 사용
print('abcdef abc abc\
 abc abc')

print()함수

문자열이나 변수 내용을 출력하는 함수이다.

변수와 변수, 혹은 변수와 문자열은 ","로 구분한다.

구분자(sep)와 끝(end)는 다음과 같이 정의한다.

print(변수1, 변수2, ..., sep=' ', end='\n')

출력 방식은

  • % 메서드
  • { } 메서드
  • f-string

%메서드

변수를 포함하는 문자열을 원하는 포맷 형태로 만든다. 변수는 %d, %f, %c등으로 바꿔쓴 후 %뒤에 변수들을 순서대로 나열한다.

a = 100
b = 2
c = a + b
print('%d + %d = %d' %(a, b, c))
print("%d + %d = %d" %(b, a, c))
print('%3d + %3d = %3d' %(a, b, c))
print('%03d + %03d = %03d' %(a, b, c))
# 문자열에 나오는 포맷의 순서와 변수의 순서가 같아야 한다.  
서식 설명
%d, %x, %o 10, 100, 234 정수(10진수, 16진수, 8진수)
%f 0.5, 1.0, 3.14 실수
%c 'b', '한' 한글자
%s '안녕', 'abcdef', 'a' 두 글자 이상인 문자열

%a.bf a는 전체 자리수, b는 소숫점 자리수, %0a.bf a는 전체 자리수이고 남는 자리수는 0으로 체운다. b는 소숫점 자리수이다.

print('%d' % 123)
print('%5d' %123)
print('%05d' %123)

print('%f' %123.45)
print('%7.1f' %123.45)
print('%7.3f' %123.45)
print('%07.1f' %123.45)

print('%s' %'Python')
print('%10s' %'Python')

{ } 메서드

print('{0} {1}' .format(a,b))

print('{0:d}' .format(123))
print('{0:5d}' .format(123))
print('{0:05d}' .format(123))

print('{0:f}' .format(123.45))
print('{0:7.1f}' .format(123.45))
print('{0:7.3f}' .format(123.45))

print('{0:s}' .format('Python'))
print('{0:>10}' .format('Python'))

import numpy as np
a = 15
print('The number is {0:d}, {0:b} in binary, {0:o} in octal and \
{0:x} in hexaldecimal form' .format(a))
print('The value of pi is approximately' + str (np.pi))
print('The value of {} is approximately {:.5f}' .format('pi', np.pi))
s = '{1:d} plus {0:d} is {2:d}' .format(2, 4, 2 + 4)
print(s)
print('Every {2} has its {3}.' .format('dog','day','rose','thorn'))
print('The third element of the list is {0[2]:g}.' .format(np.arange(10)))

f-string

v1 = 123
v2 = 123.45
v3 = 'Python'
print(f'{v1}')
print(f'{v1:5d}')
print(f'{v1:05d}')

print(f'{v2:f}')
print(f'{v2:7.1f}')
print(f'{v2:7.3f}')

print(f'{v3:s}')
print(f'{v3:>10}')
이전 글
다음 글
댓글
댓글로 소통하세요.