본문 바로가기

IT/PYTHON

Python print function

Python print function

 

간단 예

 

“Hello”를 출력하기 위해서는 다음과 같이 print() 함수를 사용한다.

>>> print(“Hello”)

Hello

 

빈 라인 출력

 

다섯 줄의 빈 라인은 다음과 같이 한다.

print(5 * “\n”)

 

 

Formatted strings

 

% 연산자는 형식화된 출력을 할 수 있다. 이것은 formatted string과 값이 필요하다. 값은 단일 값, 튜플 값, 딕셔너리 값일 수 있다. 예를 들어

print("pi=%s” % “3.14159”)

 

formatted string special character %s 같은 것으로 형변환을 할 수 있다. %s 는 값을 문자열로 바꾼다. 그래서 위의 문장을 다음과 같이 바꿀 수 있다.

print("pi=%s” % 3.14159)

 

더욱 일반적으로는 튜플에 값을 넣을 수 있다.

print("pi=%s” % (3.14159))

 

다음과 같은 형태도 가능하다.

print("%s=%s” %(“pi”, 3.14159)

 

형변환자는 값을 float, integer 등으로 변환할 수도 있다.

 

특수문자

 

특수문자는 다른언어와 유사하고 다음 표와 같다.

 

character

Decimal

Description

\

 

statement continues on next line

\

92

backslash

\’

39

Single quote

\”

34

Double quote

\a

7

Bell

\b

8

Backspace

\f

 

Formfeed

\n

10

newline

\r

13

carriage return

\t

9

tabulation

\v

11

vertical tabulation

\0 \000

 

null value

\ooo

 

octal value o in (0..7)

\xhh

 

hexadecimal value (0..9, a..f; A..F)

\uxxxx

 

Unicode character value

 

더 많은 형변환자

 

형변환자의 일반적인 구문은 다음과 같다.

%[(key)][flags][width][.prec]type

 

변환형(type)

 

문자열 변환형은 %s이다. 다음은 가능한 변환형 표이다.

character

Description

c

단일 문자로 변환

d, i

signed decimal integer 또는 long integer로 변환

u

unsigned decimal integer로 변환

e, E

지수 표기에서 부동소수점으로 변환

f

고정 십진 표기에서 부동소수점으로 변환

g

%f %e value shorter로 변환

G

%f %E value shorter로 변환

o

8진수에서 unsigned integer로 변환

r

repr()를 가진 문자열 생성

s

str() 함수를 사용해서 문자열로 변환

x, X

16진수에서 unsigned integer 로 변환

 

딕셔너리로 문자열 표현

 

>>> print(“%(key1)s and %(key2)s” % {‘key1’:1, ‘key2’:2})

“1 and 2"

 

Flags

 

character

Description

example

rendering

0

0으로 숫자만큼 채움

“(%04d) % 2

0002

-

결과를 왼쪽으로 정렬

 

 

space

양수 또는 문자열전에 공백 추가

 

 

+

항상 부호(+, -)를 가진 숫자로 시작

 

 

#

alternate 형태에서 숫자 표시

 

 

 

width option

 

width option은 최소 폭을 표시하는 양의 정수이다. 만약 변환값이 width보다 작으면 flags에 의해 왼쪽 또는 오른쪽에 공백이 추가된다.

>>> print(“(%10s)” % “example”)

(   example)

>>> print(“(%-10s)” % “example”)

(example   )

 

prec option

 

prec는 점(.) 이후에 따라오는 precision을 나타내는 양의 정수이다.

>>> print(“%.2f” % 2.012)

2.01

 

Dynamic fomatter

 

문자열을 format하고 싶은데 그것의 크기를 모를 때 * 문자를 사용하여 dynamic formatter를 사용할 수 있다.

>>> print(“%*s : %*s”, % (20, “Python”, 20, “Very Good”))

           python :           Very Good

 

 

The format string method

 

The replacement field {}

 

x = “example”

print(“{0} {1}”.format(“The”, x)

 

“The example”

{} braces와 이름(또는 index)에 의해 구별되는 replacement field이다.

 

만약 index가 주어지면, 그것은 format에서 주어지는 인자 리스트의 index이다.

x = “example”

print(“{1} {0}”.format(x, “The”)

 

“The example”

 

이름을 가진 형태는 다음과 같다.

x = “example”

print(“{first} {second}”.format(first=”The”, second=x)

 

“The example”

 

이름과 index를 가진 형태는 다음과 같다.

x = “example”

print(“{0} {second} {1}”.format(”The”, x, second=’second’)

 

“The second example”

 

주의: index는 이름 전에 주어져야 한다. 다음은 틀린 문법이다.

x = “example”

print(“{0} {second} {2}”.format(”The”, second=’second’, x)

 

딕셔너리 사용하여 깔끔하게 할 수 있는 방법

x = “example

d = {“first”: “The”, “second”: x}

print(“{0[first]} {0[second]} {1}”.format(d, “with dictionary”))

 

The example with dictionary

class attribute를 사용할 수 있다.

import math

print(“{0.pi}”.format(math))

 

3.145192….

 

변수, 리스트, 딕셔너리, attribute가 섞여있는 위치 argumnet을 사용할 수 있다.

class A():

    x = “example”

 

a = A()

print(“{0} {1[2]} {2[test]} {3.x}”.format(“This”, [“a”, “or”, “is”], {“test”:”another”}, a))

 

This is another example

 

conversion

 

string form representational form

import decimal

 

# string form

print(“{0!s}”.format(decimal.Decimal(‘3.40’))

# representational form

print(“{0!r}”.format(decimal.Decimal(‘3.40’))

 

3.40

Decimal(‘3.40’)

 

convertion의 형태

s

force string form

r

force representational form

a

force representational form using ASCII

 

 

'IT > PYTHON' 카테고리의 다른 글

Python File, Directory  (0) 2018.07.30