IT_developers

Python 개념 및 실습 - print(), format() 본문

Python

Python 개념 및 실습 - print(), format()

developers developing 2022. 9. 1. 17:00

VisualStudioCode에서 파일 만들기

파일명.py로 생성. 함수명과 똑같이 만들 수 없음.

 

1) hello.py

주석 처리 : Ctrl + / 단축키 가능

#, '''주석하고 싶은 내용''', """주석하고 싶은 내용"""

# : 한줄 주석

'''~~''', """~~""" : 문단 주석

 

2) print1.py

print() :  파이썬 화면 출력 함수

  • 기본 줄바꿈 기능
  • sep : ,로 들어오는 출력문자들의 구분을 어떻게 할 것인가?
  • end : 줄바꿈을 하지 않고 다음 줄과 연결해서 출력
  • 문자열 -  쌍따옴표, 홑따옴표 허용
 
print("Hello Python!!"
print('Hello Python!!')
print(100)
print("100")
print("25.3")
print(25)
 

# type() : 변수 타입 확인

print(type(100))   # <class 'int'>
print(type("100")) # <class 'str'>
print(type(25.5))  # <class 'float'>
print(type(True))  # <class 'bool'>
 

print('T','E','S','T') # T E S T
print('T','E','S','T', sep='') # TEST
print('2022','05','19',sep='-') #2022-05-19
print("niceman", 'naver.com', sep="@") #niceman@naver.com
 
print("파이썬은 ", end=' ')
print("쉬운 언어입니다.")

 

3) format1.py

format() 함수
  • ~~.printf("%d",3)와 같은 개념
  • %c-문자 하나, %f-실수, %d-정수, %s-문자(만능)
  • 화면에 이쁘게 출력하고 싶을 때 사용. 줄맞춰서 출력
print('%d' % 100)
print('%5d' % 100) # 5자리 맞춰서 출력
print('%05d' % 100) #5자리인데 앞자리엔 0으로 채우기
 
print("%s" %"hi")
print("%5s" %"hi")
 
print("%8.2f" % 12.21)
print("%-8.2f" % 12.21)
print("%-8.2f" % 12.2134567)
 
print("I eat %d apples" % 3)
print("I eat %s apples" % 3)
number = 4
print("I eat %d apples" % number)
print("I eat", number, "apples")
 
print("%d : %s" % (1,"홍길동"))
print("%d : %s - %f" % (2,"김성호", 93.2))
print("Test1 : %5d Price : %4.2f" % (776, 5634.123))
 
print("I eat %s apples" % 3)
print("I eat %s apples" % 3.156)
print("I eat %s apples" % 3)
print()
print("Error is %d%%" % 98) # %를 문자처럼 사용하고 싶으면 %%두개 사용
 

 

4) format2.py

  • format 함수
  • print("{}". format()) : 중괄호를 이용해 자리를 잡아두고 나중에 삽입 
  • 중괄호 안에는 숫자, 문자 사용 가능
print("{} and {}".format('You','Me')) #You and Me
print("{0} and {1} and {0}".format('You','Me')) #위치번호를 가지고 있음

# 변수명 사용

print("{var1} and {var2}".format(var1='You', var2='Me'))

print("I ate {number} apples. so I was sick for {day} days".format(number=10, day=3))
print("I ate {0} apples. so I was sick for {day} days".format(10, day=3))
# {0:5d} 와  같이 포맷 값을 같이 사용할 때는 키 값을 반드시 넣어주어야 함
print("Test1 : {0:5d}, Price : {1:4.2f}".format(776,6534.123))
# 키 값 a,b
print("Test1 : {a:5d}, Price : {b:4.2f}".format(a=776,b=6534.123))
 

 

'Python' 카테고리의 다른 글

Python 개념 및 실습 - while  (0) 2022.09.03
Python 개념 및 실습 - input  (0) 2022.09.03
Python 개념 및 실습 - 연산자  (0) 2022.09.02
Python 개념 및 실습 - escape, 변수  (0) 2022.09.02
Python 시작하기  (0) 2022.09.01
Comments