파이썬 Basic Step 3. 포맷 format [<비트코딩 라이트📙> 문제 묻.따.따.]

리온·2022년 4월 17일
1
post-thumbnail

코딩문제집 책 <비트코딩 라이트 : 파이썬> 예제들을 "묻고. 따지면서. 따라풀기." for team daiv. study

모두를 위한 쉽고 재미있는 인공지능 컨텐츠 project 🌊deep diav.
instagram @deep.daiv
/ blog deepdaiv.oopy.io
team daiv.🌸

Part1 - Basic

STEP 03 포맷 format

  • format 함수를 써서 코드를 작성하면
    여러 변수를 활용해 긴 문장을 출력할 때
    코드를 간결하게 표현할 수 있다.

  • I'm {} and work in {} . format(첫번째 {} 자리에 들어갈 내용, 두번째 {} 자리에 들어갈 내용)

  • {} 자리에 들어가는 변수의 형태는 문자열(str)도 되고 숫자(int, float 등)도 될 수 있다.

  • {} 자리에 들어가는 변수를 어떻게 출력할지를 설정할 수 있다 : {:폭.정밀도}

  • 은 글자가 들어갈 수 있는 공간(글자수), 정밀도는 보여줄 유효숫자의 개수

{:8.2} = 8개 글자가 들어가는 공간을 띄워줌, 유효숫자 2개까지만 출력

format 함수 아직 어렵다...
format 함수 상세

Example 022

name = 'Kevin'
work = 'IT company'
num1 = 5.3
num2 = 4.7517
print("I'm", name, "and work in", work) 
print("I'm {} and work in {}".format(name, work))
print("This is {:8.2}, {:8.2}".format(num1, num2))

#out

I'm Kevin and work in IT company
I'm Kevin and work in IT company
This is      5.3,      4.8

Problem 023

country = 'Korea'
population = '50M'
print('{} has about {} people'.format(country, population))

#out

Korea has about 50M people

Problem 024

#출력결과 예상하기

num1 = 1.23456789
num2 = 0.22222222
num3 = 1.87654321
num4 = 0.21314151

print("First : {:2}".format(num1)) 
#First :   1.23456789 -> 틀림
print("Second : {:10.4}".format(num2)) 
#Second :           0.222 -> 틀림
print("Third : {}".format(num3)) 
#Third : 1.87654321
print("Fourth : {:10.4}".format(num4)) 
#Fourth :           0.213 -> 틀림

#out

First : 1.23456789 #폭 0 ~ 폭 2은 똑같이 출력되는듯
Second :     0.2222 #유효숫자 4자리 : 0이 아닌 숫자 4자리인듯 
Third : 1.87654321
Fourth :     0.2131 

profile
Wannabe Starlight

0개의 댓글