매일공부

[AI 기초 다지기] 파이썬 print formatting 본문

Programming/Python

[AI 기초 다지기] 파이썬 print formatting

aram 2022. 7. 24. 19:05

형식(format)에 맞춰서 출력하고 싶을 때

1) 기본 출력

print(1,2,3) 
print("a" + " " + "b" + " " + "c")
print("a", "b", "c")

#1 2 3
#a b c
#a b c

 

2) % string

- “%datatype” % (variable) 형태로 출력 양식을 표현

print("I eat %d apples." % 3) 
print("I eat %s apples." % "five")
number = 3; day="three" 
print("I ate %d apples. I was sick for %s days." % (number, day)) 
print("Product: %s, Price per unit: %f." % ("Apple", 5.243))

#I eat 3 apples.
#I eat five apples.
#I ate 3 apples. I was sick for three days.
#####Product: Apple, Price per unit: 5.243000.

- 소수점 자릿수도 원하는 대로 하고 싶다면?

 [%숫자.소수점자f]로 정수 및 소수점 자릿수도 지정 가능

<출처> 인공지능(AI) 기초 다지기 / 부스트코스

print("Product: %s, Price per unit: %f." % ("Apple", 5.243))
#Product: Apple, Price per unit: 5.243000.

print("Product: %7s, Price per unit: %7.1f." % ("Apple", 5.243))
#Product:   Apple, Price per unit:     5.2.

> %7.1f : 7칸을 비워두고 소수점 1자리를 찍어라

 

3) format 함수

- “~~~~{datatype}~~~~”.format(argument)

age = 36; name='Sungchul Choi'
print("I’m {0} years old.".format(age)) 
#I’m 36 years old.

print("My name is {0} and {1} years old.".format(name,age)) 
#My name is Sungchul Choi and 36 years old.

print("My name is {0} and {1} years old.".format(age, name)) #변수의 순서대로 들어감
#My name is 36 and Sungchul Choi years old.

print( "Product: {0}, Price per unit: {1:.3f}.".format("Apple", 5.243))
#Product: Apple, Price per unit: 5.243.

 

- padding : 여유공간을 지정 > 글자배열 + 소수점 자릿수 맞춤(2번이랑 동일함)

<출처> 인공지능(AI) 기초 다지기 / 부스트코스

print("Product: %5s, Price per unit: %.5f." % ("Apple", 5.243)) 
#Product: Apple, Price per unit: 5.24300.
print("Product: {0:5s}, Price per unit: {1:.5f}.".format("Apple", 5.243)) 
#Product: Apple, Price per unit: 5.24300.
print("Product: %10s, Price per unit: %10.3f." % ("Apple", 5.243)) 
#Product:      Apple, Price per unit:      5.243.
print("Product: {0:>10s}, Price per unit: {1:<10.3f}.".format("Apple", 5.243))
#Product:      Apple, Price per unit: 5.243     .

- >10 : 10칸을 비우면서 왼쪽 정렬

- <10 : 10칸을 비우면서 오른쪽 정렬

 

- naming : 표시할 내용을 변수로 표시하여 입력

print("Product: %(name)10s, Price per unit: %(price)10.5f." % {"name":"Apple", "price":5.243})
#Product:      Apple, Price per unit:    5.24300.
print("Product: {name:>10s}, Price per unit:{price:10.5f}.".format(name="Apple", price=5.243))
#Product:      Apple, Price per unit:   5.24300.

 

4) fstring(대세)

- python 3.6 이후, PEP498에 근거한 formatting 기법

- f"~~~~ {datatype}~~~" : 위의 여러 방법들과 다르게 제일 앞에 f만 적어주고 datatype을 입력하면 됨

- 왼쪽 정렬이 기본값

name = "Sungchul" age = 39

print(f"Hello, {name}. You are {age}.")
#Hello, Sungchul Choi. You are 36.
print(f'{name:20}') 
#Sungchul Choi    
print(f'{name:>20}') 
#       Sungchul Choi
print(f'{name:*<20}') 
#Sungchul Choi*******
print(f'{name:*>20}') 
#*******Sungchul Choi
print(f'{name:*^20}')
#***Sungchul Choi****

number = 3.141592653589793
print(f'{number:.2f}')
#3.14

 

EX) fahrenheit

print("본 프로그램은 섭씨를 화씨로 변환해주는 프로그램입니다")
print('변환하고 싶은 섭씨 온도를 입력해 주세요:')
cel_value = float(input())
fah_value = ((9/5) * cel_value ) + 32

print(f'섭씨온도 : {cel_value:.2f}')
print(f'화씨온도 : {fah_value:.2f}')

 

 

Comments