티스토리 뷰

3.6 숫자 및 문자 서식 지정하기(Formatting Numbers and Strings)

 

우리는 format 함수를 이용해 서식화된 문자(string)를 반환 할 수 있다.

 

- 특정한 서식(format)으로 숫자를 표현해야 할 때 주로 사용한다.

- 아래와 같은 방법으로 호출한다.

 

format(요소(item), 포맷 지정자(format-specifier))

 

- 예를 들어 이자(interest)를 계산하는 프로그램을 만드는 경우

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#이자 그냥 출력
amount = 12618.98
interestRate = 0.0013
interest = amount * interestRate
print("(no format func)Interest is ", interest)
 
#round 함수를 이용한 이자 출력
amount = 12618.98
interestRate = 0.0013
interest = amount * interestRate
print("(using round func)Interest is ", round(interest,2))
 
#format 함수를 이용한 출
amount = 12618.98
interestRate = 0.0013
interest = amount * interestRate
print("(using format func)Interest is "format(interest,".2f"))
cs

 

 

- 소수점 아래 2 자리 까지 출력하고 싶을 떄, 이전엔 우리가 round함수를 이용하였다. 하지만 round 함수는 끝자리가 0이라면 출력을 하지 않는다. 즉 원하는 출력형태로 서식화 할 수가  없다.

- 하지만 format 함수를 이용한다면 우리가 원하는 형태로 서식화 할 수 있다.

- format 함수는 출력할 요소가 숫자(number)이던 문자(string), 포맷지정자format-specifier)는 문자(string)형태로 사용한다.

반환 문자(string) 형태로 반환한다.

 

3.6.1 소숫점 숫자 서식 지정하기(Formatting Floating-Point Numbers)

 

- float형태 값을 가진 데이터가 있을 떄, 우리는 지정자(specifier)를 이용해 폭(width)소수점 정밀도(precision)를 지정할 수 있다.

- 폭(width)은 필드 영역의 공백 수를 결정하고, 정밀도(precision)는 소수점 아래 표현할 숫자의 수를 결정한다.

- 폭(width)은 정수부분만을 지칭하는 것이 아닌, 소수점 아래 표현된 숫자들까지 지칭한다.

 

format(item, 폭(width).정밀도(precision)f)

 

* 소숫점 숫자 지정 예제

 

print(format(57.467657, "10.2f"))

print(format(12345678.923, "10.2f"))  #실제 폭은 11인데, 지정자는 10이 지정되어 있기 때문에 3이 생략된다.

print(format(57.4, "10.2f"))

print(format(57, "10.2f"))

 

 

3.6.2 과학표기법으로 서식 지정하기(Formatting in Scientific Notation)

 

print(format(57.467657, "10.2e"))

print(format(0.0033923, "10.2e"))

print(format(57.4, "10.2e"))

print(format(57, "10.2e"))

 

 

3.6.3 퍼센트 서식 지정하기(Formatting as a Percentage)

 

print(format(0.53457, "10.2%"))

print(format(0.0033923, "10.2%"))

print(format(7.4, "10.2%"))

print(format(57, "10.2%"))

 

 

3.6.4 서식 정의하기(Justifying Format)

 

- 기본적으로 서식은 우측(right)행으로 폭(width)을 결정한다.

- '<' 기호를 이용해 좌측(left)행으로 서식을 지정 할 수 있다.

 

print(format(57.467657, "10.2f"))

print(format(57.467657, "<10.2f”))

 

*정수 서식 지정하기(Formatting Integers)  예시에 한번 더 서식 정의 예시를 동시에 소개해놓음.

 

 

3.6.5 정수 서식 지정하기(Formatting Integers)

- 변환기호(conversion code) d, x o, b 를 이용해 정수를 10진수, 16진수, 8진수, 2진수로 변환과 동시에 서식을 지정할 수 있다.

 

print(format(59832, "10d"))
print(format(59832, "<10o"))
print(format(59832, "10x"))
print(format(59832, "<10b"))

 

 

3.6.6 문자 서식 지정하기(Formatting Strings)

 

print(format("Welcome to Python", "20s"))

print(format("Welcome to Python", "<20s"))

print(format("Welcome to Python", ">20s"))

print(format("Welcome to Python and Java", ">20s"))

 

 

 

참고 문헌 : Introduction to Programming Using Python / Y.DANIEL LIANG



본 게시물은 개인적인 용도로 작성된 게시물입니다. 이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고 개인 공부 목적으로만 이용해주시기 바랍니다.


교재 영어 원서를 직접 번역하여 정리한 게시물이므로 일부 오타, 의역이 존재할 수 있습니다. 틀린 부분이 있다면 댓글로 알려주시면 감사하겠습니다. 

댓글