[파이썬] 프롬프트를 이용한 입출력 다루기

[파이썬] 프롬프트를 이용한 입출력 다루기 updated_at: 2024-04-03 16:41

파이썬의 입출력

input

프롬프트에서 데이타를 입력 받기

width = input("사각형의 가로값(width)를 입력하세요: ")

print

데이타를 출력

print('입력한 가로값: %s' % width)

print format

  • %s : 문자형('python')
  • %d : 정수형(3)
  • %f : 실수형(3.14)

%s

문자열을 출력할때 사용

%[min]s # min이 존재할 경우 최소 자리수 공간을 확보한다.
print('Love is %s' % ('touching'))
# Love is touching
print('Love is %10s' % ('touching')) # 좌측으로 부터 최소 10자리의 자리수를 확보후 출력
# Love is   touching
print('Love is {:>10}'.format('touching')) # 위와 동일한 결과 출력
  • 공백으로 채우기
print('Love is %-10s got it?'  % ('feeling')) # 좌측으로 최소 10자리의 자리수를 확보후 출력
# Love is feeling    got it?
print('Love is {:10} got it?'.format('feeling')) # 위와 동일한 결과 출력
  • 공백대신 다른 문자로 채우기
print('{:$>10}'.format ('feeling'))
# $$$feeling
  • 가운데로 정렬
print('{:^10}'.format ('feeling'))
#  feeling  
  • 절삭
print('%.8s' % ('hellowpython')) # 8자리 이후 절삭 (hellowpy)
print('%.5s' % ('hellowpython')) # 5자리 이후 절삭 (hello)
print('%.3s' % ('hellowpython')) # 3자리 이후 후 절삭 (hel)
  • 절삭후 공백확보
print('%20.8s' % ('hellowpython')) # 20자리 공간 확보후 8자리 절삭 (hellowpy)
#             hellowpy
print('%20.5s' % ('hellowpython')) # 20자리 공간 확보후 5자리 절삭 (hello)
#                hello
print('%20.3s' % ('hellowpython')) # 20자리 공간 확보후 자리 절삭 (hel)
#                  hel

%d

정수처리하기

print('%d %d' % (1,2)) # 1 2
print('{} {}'.format(1,2)) # 1 2
  • 공백으로 채우기
print('%4d' % (50))
print('{:4d}'.format(50))
#   50

%f

실수 처리하기

print('%f' % (3.14143242225)) # 기본적으로 소수점 이하 6자리 출력
print('{:f}'.format(3.143434343434))
# 3.141432
print('%1.2f'%(3.143434343434)) # 1(정수).(2) 소수 출력을 의미
# 3.14
print('%08.2f' %(3.143434343434))  # 총 8개를 출력하는데 앞의 공백은 3으로 채운다.
print('{:08.2f}'.format(3.143434343434))
# 00003.14

다양한 format 출력

아래처럼 다양한 포맷으로 출력 가능

print('%d년 %d학기 컴퓨터프로그래밍 수업을 수강중인 학번 %d %s %s입니다.' % (year, semester, s_number, affiliation, name))

f-string(문자열 포맷)

# 문자열 맨 앞에 f를 붙이고, 출력할 변수, 값을 중괄호 안에 넣습니다.
print(f'my birthday is {year}년 {month}월 {day}일')

정렬

중괄호 {}안에 있는 변수 뒤에 콜론(:)을 붙인 후 왼쪽 정렬 (<), 오른쪽 정렬(>), 가운데 정렬(^)의 옵션을 넣어줍니다. 그 후에 자릿수를 알려주는 숫자 를 넣어주면 정렬 옵션을 사용할 수 있습니다.

str = 'pythond'

print(f'|{str:<10}|') # 왼쪽 정렬
print(f'|{str:^10}|') # 가운데 정렬
print(f'|{str:>10}|') # 오른쪽 정렬

중괄호 출력

print(f'my birthyear is {{{year}}}년')
# my birthyear is {2000}년

기타 옵션

sep(separation)

print('P','Y','T', sep='@')
# P@Y@T

end

print("hellow", end=" ")
print("python")
# hellow python
평점을 남겨주세요
평점 : 5.0
총 투표수 : 1