5. 내장형
*********

다음 섹션에서는 인터프리터에 내장된 표준형에 관해 설명합니다.

주석: Historically (until release 2.2), Python's built-in types have
  differed from user-defined types because it was not possible to use
  the built-in types as the basis for object-oriented inheritance.
  This limitation no longer exists.

The principal built-in types are numerics, sequences, mappings, files,
classes, instances and exceptions.

Some operations are supported by several object types; in particular,
practically all objects can be compared, tested for truth value, and
converted to a string (with the repr() function or the slightly
different "str()" function).  The latter function is implicitly used
when an object is written by the "print()" function.


5.1. 논리값 검사
================

Any object can be tested for truth value, for use in an "if" or
"while" condition or as operand of the Boolean operations below. The
following values are considered false:

* "None"

* "False"

* zero of any numeric type, for example, "0", "0L", "0.0", "0j".

* any empty sequence, for example, "''", "()", "[]".

* any empty mapping, for example, "{}".

* instances of user-defined classes, if the class defines a
  "__nonzero__()" or "__len__()" method, when that method returns the
  integer zero or "bool" value "False". [1]

All other values are considered true --- so objects of many types are
always true.

논리값을 돌려주는 연산과 내장 함수는 달리 명시하지 않는 한 항상 거짓의
경우 "0" 이나 "False" 를, 참이면 "1" 이나 "True" 를 돌려줍니다. (중요
한 예외: 논리 연산 "or" 와 "and" 는 항상 피연산자 중 하나를 돌려줍니다
.)


5.2. 논리 연산 --- "and", "or", "not"
=====================================

이것들은 우선순위에 따라 오름차순으로 정렬된 논리 연산들입니다:

+---------------+-----------------------------------+---------+
| 연산          | 결과                              | 노트    |
+===============+===================================+=========+
| "x or y"      | *x* 가 거짓이면 *y*, 그렇지 않으  | (1)     |
|               | 면 *x*                            |         |
+---------------+-----------------------------------+---------+
| "x and y"     | *x*가 거짓이면 *x*, 그렇지 않으면 | (2)     |
|               | *y*                               |         |
+---------------+-----------------------------------+---------+
| "not x"       | *x* 가 거짓이면 "True", 그렇지 않 | (3)     |
|               | 으면 "False"                      |         |
+---------------+-----------------------------------+---------+

노트:

1. 이것은 단락-회로 연산자이므로 첫 번째 인자가 거짓일 때만 두 번째
   의 값을 구합니다.

2. 이것은 단락-회로 연산자이므로 첫 번째 인자가 참일 때만 두 번째의
   값 을 구합니다.

3. "not" 은 비논리 연산자들보다 낮은 우선순위를 갖습니다. 그래서,
   "not a == b" 는 "not (a == b)" 로 해석되고, "a == not b" 는 문법 오
   류입 니다.


5.3. 비교
=========

Comparison operations are supported by all objects.  They all have the
same priority (which is higher than that of the Boolean operations).
Comparisons can be chained arbitrarily; for example, "x < y <= z" is
equivalent to "x < y and y <= z", except that *y* is evaluated only
once (but in both cases *z* is not evaluated at all when "x < y" is
found to be false).

이 표는 비교 연산을 요약합니다:

+--------------+---------------------------+---------+
| 연산         | 뜻                        | 노트    |
+==============+===========================+=========+
| "<"          | 엄격히 작다               |         |
+--------------+---------------------------+---------+
| "<="         | 작거나 같다               |         |
+--------------+---------------------------+---------+
| ">"          | 엄격히 크다               |         |
+--------------+---------------------------+---------+
| ">="         | 크거나 같다               |         |
+--------------+---------------------------+---------+
| "=="         | 같다                      |         |
+--------------+---------------------------+---------+
| "!="         | 같지 않다                 | (1)     |
+--------------+---------------------------+---------+
| "is"         | 객체 아이덴티티           |         |
+--------------+---------------------------+---------+
| "is not"     | 부정된 객체 아이덴티티    |         |
+--------------+---------------------------+---------+

노트:

1. "!=" can also be written "<>", but this is an obsolete usage
   kept for backwards compatibility only. New code should always use
   "!=".

Objects of different types, except different numeric types and
different string types, never compare equal; such objects are ordered
consistently but arbitrarily (so that sorting a heterogeneous array
yields a consistent result). Furthermore, some types (for example,
file objects) support only a degenerate notion of comparison where any
two objects of that type are unequal.  Again, such objects are ordered
arbitrarily but consistently. The "<", "<=", ">" and ">=" operators
will raise a "TypeError" exception when any operand is a complex
number.

Non-identical instances of a class normally compare as non-equal
unless the class defines the "__eq__()" method or the "__cmp__()"
method.

Instances of a class cannot be ordered with respect to other instances
of the same class, or other types of object, unless the class defines
either enough of the rich comparison methods ("__lt__()", "__le__()",
"__gt__()", and "__ge__()") or the "__cmp__()" method.

**CPython implementation detail:** Objects of different types except
numbers are ordered by their type names; objects of the same types
that don't support proper comparison are ordered by their address.

Two more operations with the same syntactic priority, "in" and "not
in", are supported only by sequence types (below).


5.4. Numeric Types --- "int", "float", "long", "complex"
========================================================

There are four distinct numeric types: *plain integers*, *long
integers*, *floating point numbers*, and *complex numbers*. In
addition, Booleans are a subtype of plain integers. Plain integers
(also just called *integers*) are implemented using "long" in C, which
gives them at least 32 bits of precision ("sys.maxint" is always set
to the maximum plain integer value for the current platform, the
minimum value is "-sys.maxint - 1").  Long integers have unlimited
precision.  Floating point numbers are usually implemented using
"double" in C; information about the precision and internal
representation of floating point numbers for the machine on which your
program is running is available in "sys.float_info".  Complex numbers
have a real and imaginary part, which are each a floating point
number.  To extract these parts from a complex number *z*, use
"z.real" and "z.imag". (The standard library includes additional
numeric types, "fractions" that hold rationals, and "decimal" that
hold floating-point numbers with user-definable precision.)

Numbers are created by numeric literals or as the result of built-in
functions and operators.  Unadorned integer literals (including
binary, hex, and octal numbers) yield plain integers unless the value
they denote is too large to be represented as a plain integer, in
which case they yield a long integer. Integer literals with an "'L'"
or "'l'" suffix yield long integers ("'L'" is preferred because "1l"
looks too much like eleven!).  Numeric literals containing a decimal
point or an exponent sign yield floating point numbers. Appending
"'j'" or "'J'" to a numeric literal yields an imaginary number (a
complex number with a zero real part) which you can add to an integer
or float to get a complex number with real and imaginary parts.

Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
"narrower" type is widened to that of the other, where plain integer
is narrower than long integer is narrower than floating point is
narrower than complex. Comparisons between numbers of mixed type use
the same rule. [2] The constructors "int()", "long()", "float()", and
"complex()" can be used to produce numbers of a specific type.

All built-in numeric types support the following operations. See 거듭
제곱 연산자 and later sections for the operators' priorities.

+----------------------+-----------------------------------+----------+
| 연산                 | 결과                              | 노트     |
+======================+===================================+==========+
| "x + y"              | *x* 와 *y* 의 합                  |          |
+----------------------+-----------------------------------+----------+
| "x - y"              | *x* 와 *y* 의 차                  |          |
+----------------------+-----------------------------------+----------+
| "x * y"              | *x* 와 *y* 의 곱                  |          |
+----------------------+-----------------------------------+----------+
| "x / y"              | *x* 와 *y* 의 몫                  | (1)      |
+----------------------+-----------------------------------+----------+
| "x // y"             | (floored) quotient of *x* and *y* | (4)(5)   |
+----------------------+-----------------------------------+----------+
| "x % y"              | "x / y" 의 나머지                 | (4)      |
+----------------------+-----------------------------------+----------+
| "-x"                 | 음의 *x*                          |          |
+----------------------+-----------------------------------+----------+
| "+x"                 | *x* 그대로                        |          |
+----------------------+-----------------------------------+----------+
| "abs(x)"             | *x* 의 절댓값 또는 크기           | (3)      |
+----------------------+-----------------------------------+----------+
| "int(x)"             | 정수로 변환된 *x*                 | (2)      |
+----------------------+-----------------------------------+----------+
| "long(x)"            | *x* converted to long integer     | (2)      |
+----------------------+-----------------------------------+----------+
| "float(x)"           | 실수로 변환된 *x*                 | (6)      |
+----------------------+-----------------------------------+----------+
| "complex(re,im)"     | 실수부 *re* 와 허수부 *im* 으로   |          |
|                      | 구성된 복소수. *im* 의 기본값은 0 |          |
|                      | 입니 다.                          |          |
+----------------------+-----------------------------------+----------+
| "c.conjugate()"      | conjugate of the complex number   |          |
|                      | *c*. (Identity on real numbers)   |          |
+----------------------+-----------------------------------+----------+
| "divmod(x, y)"       | 쌍 "(x // y, x % y)"              | (3)(4)   |
+----------------------+-----------------------------------+----------+
| "pow(x, y)"          | *x* 의 *y* 거듭제곱               | (3)(7)   |
+----------------------+-----------------------------------+----------+
| "x ** y"             | *x* 의 *y* 거듭제곱               | (7)      |
+----------------------+-----------------------------------+----------+

노트:

1. For (plain or long) integer division, the result is an integer.
   The result is always rounded towards minus infinity: 1/2 is 0,
   (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.  Note that the
   result is a long integer if either operand is a long integer,
   regardless of the numeric value.

2. Conversion from floats using "int()" or "long()" truncates
   toward zero like the related function, "math.trunc()".  Use the
   function "math.floor()" to round downward and "math.ceil()" to
   round upward.

3. See 내장 함수 for a full description.

4. 버전 2.3 폐지: The floor division operator, the modulo operator,
   and the "divmod()" function are no longer defined for complex
   numbers.  Instead, convert to a floating point number using the
   "abs()" function if appropriate.

5. Also referred to as integer division.  The resultant value is a
   whole integer, though the result's type is not necessarily int.

6. float는 또한 숫자가 아님(NaN)과 양 또는 음의 무한대를 나타내는
   문자 열 "nan"과 접두사 "+" 나 "-" 가 선택적으로 붙을 수 있는 "inf"
   를 받 아들입니다.

   버전 2.6에 추가.

7. 파이썬은 프로그래밍 언어들에서 흔히 그렇듯이, 있는 것처럼
   "pow(0, 0)" 와 "0 ** 0" 이 "1" 이 되도록 정의합니다.

All "numbers.Real" types ("int", "long", and "float") also include the
following operations:

+----------------------+-----------------------------------------------+
| 연산                 | 결과                                          |
+======================+===============================================+
| "math.trunc(x)"      | *x* 는 "Integral" 로 잘립니다                 |
+----------------------+-----------------------------------------------+
| "round(x[, n])"      | *x* rounded to *n* digits, rounding ties away |
|                      | from zero. If *n* is omitted, it defaults to  |
|                      | 0.                                            |
+----------------------+-----------------------------------------------+
| "math.floor(x)"      | the greatest integer as a float <= *x*        |
+----------------------+-----------------------------------------------+
| "math.ceil(x)"       | the least integer as a float >= *x*           |
+----------------------+-----------------------------------------------+


5.4.1. 정수 형에 대한 비트 연산
-------------------------------

Bitwise operations only make sense for integers.  Negative numbers are
treated as their 2's complement value (this assumes a sufficiently
large number of bits that no overflow occurs during the operation).

이진 비트 연산의 우선순위는 모두 숫자 연산보다 낮고 비교보다 높습니다;
일항 연산 "~" 은 다른 일항 연산들 ("+" 와 "-") 과 같은 우선순위를 가집
니다.

이 표는 비트 연산을 나열하는데, 우선순위에 따라 오름차순으로 정렬되어
있습니다:

+--------------+----------------------------------+------------+
| 연산         | 결과                             | 노트       |
+==============+==================================+============+
| "x | y"      | *x* 와 *y* 의 비트별 *or*        |            |
+--------------+----------------------------------+------------+
| "x ^ y"      | *x* 와 *y* 의 비트별 *배타적 or  |            |
|              | (exclusive or)*                  |            |
+--------------+----------------------------------+------------+
| "x & y"      | *x* 와 *y* 의 비트별 *and*       |            |
+--------------+----------------------------------+------------+
| "x << n"     | *x* 를 *n* 비트만큼 왼쪽으로 시  | (1)(2)     |
|              | 프트                             |            |
+--------------+----------------------------------+------------+
| "x >> n"     | *x* 를 *n* 비트만큼 오른쪽으로   | (1)(3)     |
|              | 시프트                           |            |
+--------------+----------------------------------+------------+
| "~x"         | *x* 의 비트 반전                 |            |
+--------------+----------------------------------+------------+

노트:

1. 음의 시프트 수는 허락되지 않고 "ValueError" 를 일으킵니다.

2. A left shift by *n* bits is equivalent to multiplication by
   "pow(2, n)".  A long integer is returned if the result exceeds the
   range of plain integers.

3. A right shift by *n* bits is equivalent to division by "pow(2,
   n)".


5.4.2. 정수 형에 대한 추가 메서드
---------------------------------

The integer types implement the "numbers.Integral" *abstract base
class*. In addition, they provide one more method:

int.bit_length()

long.bit_length()

   부호와 선행 0을 제외하고, 이진수로 정수를 나타내는 데 필요한 비트
   수를 돌려줍니다:

      >>> n = -37
      >>> bin(n)
      '-0b100101'
      >>> n.bit_length()
      6

   좀 더 정확하게 말하자면, "x" 가 0이 아니면, "x.bit_length()" 는
   "2**(k-1) <= abs(x) < 2**k" 를 만족하는 유일한 양의 정수 "k" 입니다
   . 동등하게, "abs(x)" 가 정확하게 반올림된 로그값을 가질 만큼 아주
   작으면, "k = 1 + int(log(abs(x), 2))" 가 됩니다. "x" 가 0이면,
   "x.bit_length()" 는 "0" 을 돌려줍니다.

   다음 코드와 동등합니다:

      def bit_length(self):
          s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
          s = s.lstrip('-0b') # remove leading zeros and minus sign
          return len(s)       # len('100101') --> 6

   버전 2.7에 추가.


5.4.3. 실수에 대한 추가 메서드
------------------------------

float 형은 "numbers.Real" *추상 베이스 클래스* 를 구현합니다. 또한,
float는 다음과 같은 추가 메서드를 갖습니다.

float.as_integer_ratio()

   비율이 원래 float와 정확히 같고 양의 분모를 갖는 정수 쌍을 돌려줍니
   다. 무한대에는 "OverflowError" 를, NaN 에는 a "ValueError" 를 일으
   킵니다.

   버전 2.6에 추가.

float.is_integer()

   float 인스턴스가 정숫값을 가진 유한이면 "True" 를, 그렇지 않으면
   "False" 를 돌려줍니다:

      >>> (-2.0).is_integer()
      True
      >>> (3.2).is_integer()
      False

   버전 2.6에 추가.

두 가지 메서드가 16진수 문자열과의 변환을 지원합니다. 파이썬의 float는
내부적으로 이진수로 저장되기 때문에 float를 *십진수* 문자열로 또는 그
반대로 변환하는 것은 보통 반올림 오류를 수반합니다. 이에 반해, 16진수
문자열은 부동 소수점 숫자의 정확한 표현과 지정을 가능하게 합니다. 이것
은 디버깅 및 수치 작업에 유용할 수 있습니다.

float.hex()

   부동 소수점의 16진수 문자열 표현을 돌려줍니다. 유한 부동 소수점의
   경우, 이 표현은 항상 선행하는 "0x" 와 후행하는 "p" 와 지수를 포함합
   니다.

   버전 2.6에 추가.

float.fromhex(s)

   16진수 문자열 *s* 로 표현되는 float를 돌려주는 클래스 메서드. 문자
   열 *s* 는 앞뒤 공백을 가질 수 있습니다.

   버전 2.6에 추가.

"float.hex()" 는 인스턴스 메서드인 반면, "float.fromhex()" 는 클래스
메서드임에 주의하세요.

16진수 문자열은 다음과 같은 형식을 취합니다:

   [sign] ['0x'] integer ['.' fraction] ['p' exponent]

선택적인 "sign" 은 "+" 나 "-" 가 될 수 있고, "integer" 와 "fraction"
은 16진수 문자열이고, "exponent" 는 선택적인 선행 부호가 붙을 수 있는
십진수입니다. 대소 문자는 중요하지 않으며 integer 나 fraction 중 어느
하나에 적어도 하나의 16진수가 있어야 합니다. 이 문법은 C99 표준의
6.4.4.2 절에 지정된 문법과 비슷하며, 자바 1.5 이상에서 사용되는 문법과
도 비슷합니다. 특히, "float.hex()" 의 출력은 C 또는 자바 코드에서 16진
수의 부동 소수점 리터럴로 사용할 수 있으며, C의 "%a" 포맷 문자나 자바
의 "Double.toHexString" 가 만들어내는 16진수 문자열은
"float.fromhex()" 가 받아들입니다.

지수는 16진수가 아닌 십진수로 쓰이고, 숫자에 곱해지는 2의 거듭제곱을
제공한다는 점에 유의하십시오. 예를 들어, 16진수 문자열 "0x3.a7p10" 는
부동 소수점 숫자 "(3 + 10./16 + 7./16**2) * 2.0**10" 또는 "3740.0" 를
나타냅니다:

   >>> float.fromhex('0x3.a7p10')
   3740.0

"3740.0" 에 역변환을 적용하면 같은 숫자를 나타내는 다른 16진수 문자열
을 얻을 수 있습니다:

   >>> float.hex(3740.0)
   '0x1.d380000000000p+11'


5.5. 이터레이터 형
==================

버전 2.2에 추가.

파이썬은 컨테이너에 대한 이터레이션 개념을 지원합니다. 이것은 두 개의
메서드를 사용해서 구현됩니다; 이것들은 사용자 정의 클래스가 이터레이션
을 지원할 수 있도록 하는 데 사용됩니다. 아래에서 더 자세히 설명할 시퀀
스는 항상 이터레이션 메서드를 지원합니다.

컨테이너 객체가 이터레이션 지원을 제공하려면 한가지 메서드를 정의할 필
요가 있습니다.:

container.__iter__()

   이터레이터 객체를 돌려줍니다. 이 객체는 아래에서 설명하는 이터레이
   터 프로토콜을 지원해야 합니다. 컨테이너가 여러 유형의 이터레이션을
   지원하는 경우, 이터레이션 유형에 대한 이터레이터를 구체적으로 요구
   하는 추가 메서드를 제공할 수 있습니다. (여러 형태의 이터레이션을 지
   원하는 객체의 예로 너비 우선과 깊이 우선 탐색을 모두 지원하는 트리
   구조를 들 수 있습니다.) 이 메서드는 파이썬/C API에서 파이썬 객체를
   위한 구조체의 "tp_iter" 슬롯에 대응합니다.

이터레이터 객체 자체는 다음과 같은 두 가지 메서드를 지원해야 하는데,
둘이 함께 *이터레이터 프로토콜 (iterator protocol)* 를 이룹니다.:

iterator.__iter__()

   이터레이터 객체 자신을 돌려줍니다. 이는 "for" 와 "in" 문에 컨테이너
   와 이터레이터 모두 사용될 수 있게 하는 데 필요합니다. 이 메서드는
   파이썬/C API에서 파이썬 객체를 위한 구조체의 "tp_iter" 슬롯에 대응
   합니다.

iterator.next()

   컨테이너의 다음 항목을 돌려줍니다. 더 항목이 없으면 "StopIteration"
   예외를 일으킵니다. 이 메서드는 파이썬/C API에서 파이썬 객체를 위한
   구조체의 "tp_iternext" 슬롯에 대응합니다.

파이썬은 일반적이거나 특정한 시퀀스 형, 딕셔너리, 기타 더 특화된 형태
에 대한 이터레이션을 지원하기 위해 여러 이터레이터 객체를 정의합니다.
이터레이터 프로토콜의 구현을 넘어서 개별적인 형이 중요하지는 않습니다.

The intention of the protocol is that once an iterator's "next()"
method raises "StopIteration", it will continue to do so on subsequent
calls. Implementations that do not obey this property are deemed
broken.  (This constraint was added in Python 2.3; in Python 2.2,
various iterators are broken according to this rule.)


5.5.1. 제너레이터 형
--------------------

Python's *generator*s provide a convenient way to implement the
iterator protocol.  If a container object's "__iter__()" method is
implemented as a generator, it will automatically return an iterator
object (technically, a generator object) supplying the "__iter__()"
and "next()" methods.  More information about generators can be found
in the documentation for the yield expression.


5.6. Sequence Types --- "str", "unicode", "list", "tuple", "bytearray", "buffer", "xrange"
==========================================================================================

There are seven sequence types: strings, Unicode strings, lists,
tuples, bytearrays, buffers, and xrange objects.

For other containers see the built in "dict" and "set" classes, and
the "collections" module.

String literals are written in single or double quotes: "'xyzzy'",
""frobozz"".  See String literals for more about string literals.
Unicode strings are much like strings, but are specified in the syntax
using a preceding "'u'" character: "u'abc'", "u"def"". In addition to
the functionality described here, there are also string-specific
methods described in the 문자열 메서드 section. Lists are constructed
with square brackets, separating items with commas: "[a, b, c]".
Tuples are constructed by the comma operator (not within square
brackets), with or without enclosing parentheses, but an empty tuple
must have the enclosing parentheses, such as "a, b, c" or "()".  A
single item tuple must have a trailing comma, such as "(d,)".

Bytearray objects are created with the built-in function
"bytearray()".

Buffer objects are not directly supported by Python syntax, but can be
created by calling the built-in function "buffer()".  They don't
support concatenation or repetition.

Objects of type xrange are similar to buffers in that there is no
specific syntax to create them, but they are created using the
"xrange()" function.  They don't support slicing, concatenation or
repetition, and using "in", "not in", "min()" or "max()" on them is
inefficient.

Most sequence types support the following operations.  The "in" and
"not in" operations have the same priorities as the comparison
operations.  The "+" and "*" operations have the same priority as the
corresponding numeric operations. [3] Additional methods are provided
for 가변 시퀀스 형.

This table lists the sequence operations sorted in ascending priority.
In the table, *s* and *t* are sequences of the same type; *n*, *i* and
*j* are integers:

+--------------------+----------------------------------+------------+
| 연산               | 결과                             | 노트       |
+====================+==================================+============+
| "x in s"           | *s* 의 항목 중 하나가 *x* 와 같  | (1)        |
|                    | 으면 "True", 그렇지 않으면       |            |
|                    | "False"                          |            |
+--------------------+----------------------------------+------------+
| "x not in s"       | *s* 의 항목 중 하나가 *x* 와 같  | (1)        |
|                    | 으면 "False", 그렇지 않으면      |            |
|                    | "True"                           |            |
+--------------------+----------------------------------+------------+
| "s + t"            | *s* 와 *t* 의 이어 붙이기        | (6)        |
+--------------------+----------------------------------+------------+
| "s * n, n * s"     | *s* 를 그 자신에 *n* 번 더하는   | (2)        |
|                    | 것과 같습니다                    |            |
+--------------------+----------------------------------+------------+
| "s[i]"             | *s* 의 *i* 번째 항목, 0에서 시작 | (3)        |
|                    | 합니다                           |            |
+--------------------+----------------------------------+------------+
| "s[i:j]"           | *s* 의 *i* 에서 *j* 까지의 슬라  | (3)(4)     |
|                    | 이스                             |            |
+--------------------+----------------------------------+------------+
| "s[i:j:k]"         | *s* 의 *i* 에서 *j* 까지 스텝    | (3)(5)     |
|                    | *k* 의 슬라이스                  |            |
+--------------------+----------------------------------+------------+
| "len(s)"           | *s* 의 길이                      |            |
+--------------------+----------------------------------+------------+
| "min(s)"           | *s* 의 가장 작은 항목            |            |
+--------------------+----------------------------------+------------+
| "max(s)"           | *s* 의 가장 큰 항목              |            |
+--------------------+----------------------------------+------------+
| "s.index(x)"       | index of the first occurrence of |            |
|                    | *x* in *s*                       |            |
+--------------------+----------------------------------+------------+
| "s.count(x)"       | *s* 등장하는 *x* 의 총수         |            |
+--------------------+----------------------------------+------------+

Sequence types also support comparisons. In particular, tuples and
lists are compared lexicographically by comparing corresponding
elements. This means that to compare equal, every element must compare
equal and the two sequences must be of the same type and have the same
length. (For full details see 비교 in the language reference.)

노트:

1. When *s* is a string or Unicode string object the "in" and "not
   in" operations act like a substring test.  In Python versions
   before 2.3, *x* had to be a string of length 1. In Python 2.3 and
   beyond, *x* may be a string of any length.

2. Values of *n* less than "0" are treated as "0" (which yields an
   empty sequence of the same type as *s*).  Note that items in the
   sequence *s* are not copied; they are referenced multiple times.
   This often haunts new Python programmers; consider:

   >>> lists = [[]] * 3
   >>> lists
   [[], [], []]
   >>> lists[0].append(3)
   >>> lists
   [[3], [3], [3]]

   What has happened is that "[[]]" is a one-element list containing
   an empty list, so all three elements of "[[]] * 3" are references
   to this single empty list.  Modifying any of the elements of
   "lists" modifies this single list. You can create a list of
   different lists this way:

   >>> lists = [[] for i in range(3)]
   >>> lists[0].append(3)
   >>> lists[1].append(5)
   >>> lists[2].append(7)
   >>> lists
   [[3], [5], [7]]

   더 자세한 설명은 FAQ 항목 How do I create a multidimensional list?
   에서 얻을 수 있습니다.

3. *i* 또는 *j* 가 음수인 경우, 인덱스는 시퀀스 *s* 의 끝에 상대적
   입니 다: "len(s) + i" 이나 "len(s) + j" 로 치환됩니다. 하지만 "-0"
   은 여 전히 "0" 입니다.

4. *i* 에서 *j* 까지의 *s* 의 슬라이스는 "i <= k < j" 를 만족하는
   인덱 스 *k* 의 항목들로 구성된 시퀀스로 정의됩니다. *i* 또는 *j* 가
   "len(s)" 보다 크면 "len(s)" 을 사용합니다. *i* 가 생략되거나 "None"
   이라면 "0" 을 사용합니다. *j* 가 생략되거나 "None" 이면 "len(s)" 을
   사용합니다. *i* 가 *j* 보다 크거나 같으면 빈 슬라이스가 됩니다.

5. 스텝 *k* 가 있는 *i* 에서 *j* 까지의 슬라이스는 "0 <= n <
   (j-i)/k" 를 만족하는 인덱스 "x = i + n*k" 의 항목들로 구성된 시퀀스
   로 정의됩 니다. 다시 말하면, 인덱스는 "i", "i+k", "i+2*k", "i+3*k"
   등이며 *j* 에 도달할 때 멈춥니다 (하지만 절대 *j* 를 포함하지는 않
   습니다). *k* 가 양수면 *i* 와 *j* 는 더 큰 경우 "len(s)" 로 줄어듭
   니다. *k* 가 음수면, *i* 와 *j* 는 더 큰 경우 "len(s) - 1" 로 줄어
   듭니다. *i* 또 는 *j* 가 생략되거나 "None" 이면, 그것들은 "끝" 값이
   됩니다 (끝은 *k* 의 부호에 따라 달라집니다). *k* 는 0일 수 없음에
   주의하세요. *k* 가 "None" 이면 "1" 로 취급됩니다.

6. **CPython implementation detail:** If *s* and *t* are both
   strings, some Python implementations such as CPython can usually
   perform an in-place optimization for assignments of the form "s = s
   + t" or "s += t".  When applicable, this optimization makes
   quadratic run-time much less likely.  This optimization is both
   version and implementation dependent.  For performance sensitive
   code, it is preferable to use the "str.join()" method which assures
   consistent linear concatenation performance across versions and
   implementations.

   버전 2.4으로 변경: Formerly, string concatenation never occurred
   in-place.


5.6.1. 문자열 메서드
--------------------

Below are listed the string methods which both 8-bit strings and
Unicode objects support.  Some of them are also available on
"bytearray" objects.

In addition, Python's strings support the sequence type methods
described in the Sequence Types --- str, unicode, list, tuple,
bytearray, buffer, xrange section. To output formatted strings use
template strings or the "%" operator described in the String
Formatting Operations section. Also, see the "re" module for string
functions based on regular expressions.

str.capitalize()

   첫 문자가 대문자이고 나머지가 소문자인 문자열의 복사본을 돌려줍니다
   .

   For 8-bit strings, this method is locale-dependent.

str.center(width[, fillchar])

   Return centered in a string of length *width*. Padding is done
   using the specified *fillchar* (default is a space).

   버전 2.4으로 변경: Support for the *fillchar* argument.

str.count(sub[, start[, end]])

   범위 [*start*, *end*] 에서 서브 스트링 *sub* 가 중첩되지 않고 등장
   하는 횟수를 돌려줍니다. 선택적 인자 *start* 와 *end* 는 슬라이스 표
   기법으로 해석됩니다.

str.decode([encoding[, errors]])

   Decodes the string using the codec registered for *encoding*.
   *encoding* defaults to the default string encoding.  *errors* may
   be given to set a different error handling scheme.  The default is
   "'strict'", meaning that encoding errors raise "UnicodeError".
   Other possible values are "'ignore'", "'replace'" and any other
   name registered via "codecs.register_error()", see section Codec
   Base Classes.

   버전 2.2에 추가.

   버전 2.3으로 변경: Support for other error handling schemes added.

   버전 2.7으로 변경: 키워드 인자 지원이 추가되었습니다.

str.encode([encoding[, errors]])

   Return an encoded version of the string.  Default encoding is the
   current default string encoding.  *errors* may be given to set a
   different error handling scheme.  The default for *errors* is
   "'strict'", meaning that encoding errors raise a "UnicodeError".
   Other possible values are "'ignore'", "'replace'",
   "'xmlcharrefreplace'", "'backslashreplace'" and any other name
   registered via "codecs.register_error()", see section Codec Base
   Classes. For a list of possible encodings, see section Standard
   Encodings.

   버전 2.0에 추가.

   버전 2.3으로 변경: Support for "'xmlcharrefreplace'" and
   "'backslashreplace'" and other error handling schemes added.

   버전 2.7으로 변경: 키워드 인자 지원이 추가되었습니다.

str.endswith(suffix[, start[, end]])

   문자열이 지정된 *suffix* 로 끝나면 "True" 를 돌려주고, 그렇지 않으
   면 "False" 를 돌려줍니다. *suffix* 는 찾고자 하는 접미사들의 튜플이
   될 수도 있습니다. 선택적 *start* 가 제공되면 그 위치에서 검사를 시
   작합니다. 선택적 *end* 를 사용하면 해당 위치에서 비교를 중단합니다.

   버전 2.5으로 변경: Accept tuples as *suffix*.

str.expandtabs([tabsize])

   모든 탭 문자들을 현재의 열과 주어진 탭 크기에 따라 하나나 그 이상의
   스페이스로 치환한 문자열의 복사본을 돌려줍니다. 탭 위치는 *tabsize*
   문자마다 발생합니다 (기본값은 8이고, 열 0, 8, 16 등에 탭 위치를 지
   정합니다). 문자열을 확장하기 위해 현재 열이 0으로 설정되고 문자열을
   문자 단위로 검사합니다. 문자가 탭 ("\t") 이면, 현재 열이 다음 탭 위
   치와 같아질 때까지 하나 이상의 스페이스 문자가 삽입됩니다. (탭 문자
   자체는 복사되지 않습니다.) 문자가 개행 문자 ("\n") 또는 캐리지 리턴
   ("\r") 이면 복사되고 현재 열은 0으로 재설정됩니다. 다른 문자는 변경
   되지 않고 복사되고 현재 열은 인쇄할 때 문자가 어떻게 표시되는지에
   관계없이 1씩 증가합니다.

   >>> '01\t012\t0123\t01234'.expandtabs()
   '01      012     0123    01234'
   >>> '01\t012\t0123\t01234'.expandtabs(4)
   '01  012 0123    01234'

str.find(sub[, start[, end]])

   서브 스트링 *sub* 가 슬라이스 "s[start:end]" 내에 등장하는 가장 작
   은 문자열의 인덱스를 돌려줍니다. 선택적 인자 *start* 와 *end* 는 슬
   라이스 표기법으로 해석됩니다. *sub* 가 없으면 "-1" 을 돌려줍니다.

   주석: "find()" 메서드는 *sub* 의 위치를 ​​알아야 할 경우에만 사용
     해야 합니다. *sub* 가 서브 스트링인지 확인하려면 "in" 연산자를 사
     용하 십시오:

        >>> 'Py' in 'Python'
        True

str.format(*args, **kwargs)

   문자열 포맷 연산을 수행합니다. 이 메서드가 호출되는 문자열은 리터럴
   텍스트나 중괄호 "{}" 로 구분된 치환 필드를 포함할 수 있습니다. 각
   치환 필드는 위치 인자의 숫자 인덱스나 키워드 인자의 이름을 가질 수
   있습니다. 각 치환 필드를 해당 인자의 문자열 값으로 치환한 문자열의
   사본을 돌려줍니다.

   >>> "The sum of 1 + 2 is {0}".format(1+2)
   'The sum of 1 + 2 is 3'

   포맷 문자열에 지정할 수 있는 다양한 포맷 옵션에 대한 설명은 Format
   String Syntax 을 참조하십시오.

   This method of string formatting is the new standard in Python 3,
   and should be preferred to the "%" formatting described in String
   Formatting Operations in new code.

   버전 2.6에 추가.

str.index(sub[, start[, end]])

   Like "find()", but raise "ValueError" when the substring is not
   found.

str.isalnum()

   Return true if all characters in the string are alphanumeric and
   there is at least one character, false otherwise.

   For 8-bit strings, this method is locale-dependent.

str.isalpha()

   Return true if all characters in the string are alphabetic and
   there is at least one character, false otherwise.

   For 8-bit strings, this method is locale-dependent.

str.isdigit()

   Return true if all characters in the string are digits and there is
   at least one character, false otherwise.

   For 8-bit strings, this method is locale-dependent.

str.islower()

   문자열 내의 모든 케이스 문자가 [4] 소문자이고, 적어도 하나의 케이스
   문자가 존재하는 경우 참을 돌려주고, 그렇지 않으면 거짓을 돌려줍니다
   .

   For 8-bit strings, this method is locale-dependent.

str.isspace()

   Return true if there are only whitespace characters in the string
   and there is at least one character, false otherwise.

   For 8-bit strings, this method is locale-dependent.

str.istitle()

   문자열이 제목 케이스 문자열이고 하나 이상의 문자가 있는 경우 참을
   돌려줍니다. 예를 들어 대문자 앞에는 케이스 없는 문자만 올 수 있고
   소문자는 케이스 문자 뒤에만 올 수 있습니다. 그렇지 않은 경우는 거짓
   을 돌려줍니다.

   For 8-bit strings, this method is locale-dependent.

str.isupper()

   문자열 내의 모든 케이스 문자가 [4] 대문자이고, 적어도 하나의 케이스
   문자가 존재하는 경우 참을 돌려주고, 그렇지 않으면 거짓을 돌려줍니다
   .

   For 8-bit strings, this method is locale-dependent.

str.join(iterable)

   Return a string which is the concatenation of the strings in
   *iterable*. If there is any Unicode object in *iterable*, return a
   Unicode instead. A "TypeError" will be raised if there are any non-
   string or non Unicode object values in *iterable*.  The separator
   between elements is the string providing this method.

str.ljust(width[, fillchar])

   Return the string left justified in a string of length *width*.
   Padding is done using the specified *fillchar* (default is a
   space).  The original string is returned if *width* is less than or
   equal to "len(s)".

   버전 2.4으로 변경: Support for the *fillchar* argument.

str.lower()

   모든 케이스 문자 [4] 가 소문자로 변환된 문자열의 복사본을 돌려줍니
   다.

   For 8-bit strings, this method is locale-dependent.

str.lstrip([chars])

   Return a copy of the string with leading characters removed.  The
   *chars* argument is a string specifying the set of characters to be
   removed.  If omitted or "None", the *chars* argument defaults to
   removing whitespace.  The *chars* argument is not a prefix; rather,
   all combinations of its values are stripped:

   >>> '   spacious   '.lstrip()
   'spacious   '
   >>> 'www.example.com'.lstrip('cmowz.')
   'example.com'

   버전 2.2.2으로 변경: Support for the *chars* argument.

str.partition(sep)

   *sep* 가 처음 나타나는 위치에서 문자열을 나누고, 구분자 앞에 있는
   부분, 구분자 자체, 구분자 뒤에 오는 부분으로 구성된 3-튜플을 돌려줍
   니다. 구분자가 발견되지 않으면, 문자열 자신과 그 뒤를 따르는 두 개
   의 빈 문자열로 구성된 3-튜플을 돌려줍니다.

   버전 2.5에 추가.

str.replace(old, new[, count])

   모든 서브 스트링 *old* 가 *new* 로 치환된 문자열의 복사본을 돌려줍
   니다. 선택적 인자 *count* 가 주어지면, 앞의 *count* 개만 치환됩니다
   .

str.rfind(sub[, start[, end]])

   서브 스트링 *sub* 가 "s[start:end]" 내에 등장하는 가장 큰 문자열의
   인덱스를 돌려줍니다. 선택적 인자 *start* 와 *end* 는 슬라이스 표기
   법으로 해석됩니다. 실패하면 "-1" 을 돌려줍니다.

str.rindex(sub[, start[, end]])

   "rfind()"와 비슷하지만, 서브 스트링 *sub* 를 찾을 수 없는 경우
   "ValueError" 를 일으킵니다.

str.rjust(width[, fillchar])

   Return the string right justified in a string of length *width*.
   Padding is done using the specified *fillchar* (default is a
   space). The original string is returned if *width* is less than or
   equal to "len(s)".

   버전 2.4으로 변경: Support for the *fillchar* argument.

str.rpartition(sep)

   *sep* 가 마지막으로 나타나는 위치에서 문자열을 나누고, 구분자 앞에
   있는 부분, 구분자 자체, 구분자 뒤에 오는 부분으로 구성된 3-튜플을
   돌려줍니다. 구분자가 발견되지 않으면, 두 개의 빈 문자열과 그 뒤를
   따르는 문자열 자신으로 구성된 3-튜플을 돌려줍니다.

   버전 2.5에 추가.

str.rsplit([sep[, maxsplit]])

   *sep* 를 구분자 문자열로 사용하여 문자열에 있는 단어들의 리스트를
   돌려줍니다. *maxsplit* 이 주어지면 가장 오른쪽에서 최대 *maxsplit*
   번의 분할이 수행됩니다. *sep* 이 지정되지 않거나 "None" 이면, 구분
   자로 모든 공백 문자가 사용됩니다. 오른쪽에서 분리하는 것을 제외하면
   , "rsplit()"는 아래에서 자세히 설명될 "split()"처럼 동작합니다.

   버전 2.4에 추가.

str.rstrip([chars])

   Return a copy of the string with trailing characters removed.  The
   *chars* argument is a string specifying the set of characters to be
   removed.  If omitted or "None", the *chars* argument defaults to
   removing whitespace.  The *chars* argument is not a suffix; rather,
   all combinations of its values are stripped:

   >>> '   spacious   '.rstrip()
   '   spacious'
   >>> 'mississippi'.rstrip('ipz')
   'mississ'

   버전 2.2.2으로 변경: Support for the *chars* argument.

str.split([sep[, maxsplit]])

   *sep* 를 구분자 문자열로 사용하여 문자열에 있는 단어들의 리스트를
   돌려줍니다. *maxsplit* 이 주어지면 최대 *maxsplit* 번의 분할이 수행
   됩니다 (따라서, 리스트는 최대 "maxsplit+1" 개의 요소를 가지게 됩니
   다). *maxsplit* 이 지정되지 않았거나 "-1" 이라면 분할 수에 제한이
   없습니다 (가능한 모든 분할이 만들어집니다).

   *sep* 이 주어지면, 연속된 구분자는 묶이지 않고 빈 문자열을 구분하는
   것으로 간주합니다 (예를 들어, "'1,,2'.split(',')" 는 "['1', '',
   '2']" 를 돌려줍니다). *sep* 인자는 여러 문자로 구성될 수 있습니다 (
   예를 들어, "'1<>2<>3'.split('<>')" 는 "['1', '2', '3']" 를 돌려줍니
   다). 지정된 구분자로 빈 문자열을 나누면 "['']" 를 돌려줍니다.

   *sep* 이 지정되지 않거나 "None" 이면, 다른 분할 알고리즘이 적용됩니
   다: 연속된 공백 문자는 단일한 구분자로 간주하고, 문자열이 선행이나
   후행 공백을 포함해도 결과는 시작과 끝에 빈 문자열을 포함하지 않습니
   다. 결과적으로, 빈 문자열이나 공백만으로 구성된 문자열을 "None" 구
   분자로 나누면 "[]" 를 돌려줍니다.

   For example, "' 1  2   3  '.split()" returns "['1', '2', '3']", and
   "'  1  2   3  '.split(None, 1)" returns "['1', '2   3  ']".

str.splitlines([keepends])

   Return a list of the lines in the string, breaking at line
   boundaries. This method uses the *universal newlines* approach to
   splitting lines. Line breaks are not included in the resulting list
   unless *keepends* is given and true.

   Python recognizes ""\r"", ""\n"", and ""\r\n"" as line boundaries
   for 8-bit strings.

   예를 들면:

      >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
      ['ab c', '', 'de fg', 'kl']
      >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
      ['ab c\n', '\n', 'de fg\r', 'kl\r\n']

   구분자 문자열 *sep* 이 주어졌을 때 "split()" 와 달리, 이 메서드는
   빈 문자열에 대해서 빈 리스트를 돌려주고, 마지막 줄 바꿈은 새 줄을
   만들지 않습니다:

      >>> "".splitlines()
      []
      >>> "One line\n".splitlines()
      ['One line']

   비교해 보면, "split('\n')" 는 이렇게 됩니다:

      >>> ''.split('\n')
      ['']
      >>> 'Two lines\n'.split('\n')
      ['Two lines', '']

unicode.splitlines([keepends])

   Return a list of the lines in the string, like "str.splitlines()".
   However, the Unicode method splits on the following line
   boundaries, which are a superset of the *universal newlines*
   recognized for 8-bit strings.

   +-------------------------+-------------------------------+
   | 표현                    | 설명                          |
   +=========================+===============================+
   | "\n"                    | 줄 넘김                       |
   +-------------------------+-------------------------------+
   | "\r"                    | 캐리지 리턴                   |
   +-------------------------+-------------------------------+
   | "\r\n"                  | 캐리지 리턴 + 줄 넘김         |
   +-------------------------+-------------------------------+
   | "\v" 또는 "\x0b"        | 수직 탭                       |
   +-------------------------+-------------------------------+
   | "\f" 또는 "\x0c"        | 폼 피드                       |
   +-------------------------+-------------------------------+
   | "\x1c"                  | 파일 구분자                   |
   +-------------------------+-------------------------------+
   | "\x1d"                  | 그룹 구분자                   |
   +-------------------------+-------------------------------+
   | "\x1e"                  | 레코드 구분자                 |
   +-------------------------+-------------------------------+
   | "\x85"                  | 다음 줄 (C1 제어 코드)        |
   +-------------------------+-------------------------------+
   | "\u2028"                | 줄 구분자                     |
   +-------------------------+-------------------------------+
   | "\u2029"                | 문단 구분자                   |
   +-------------------------+-------------------------------+

   버전 2.7으로 변경: "\v" 와 "\f" 를 줄 경계 목록에 추가했습니다.

str.startswith(prefix[, start[, end]])

   문자열이 지정된 *prefix* 로 시작하면 "True" 를 돌려주고, 그렇지 않
   으면 "False" 를 돌려줍니다. *prefix* 는 찾고자 하는 접두사들의 튜플
   이 될 수도 있습니다. 선택적 *start* 가 제공되면 그 위치에서 검사를
   시작합니다. 선택적 *end* 를 사용하면 해당 위치에서 비교를 중단합니
   다.

   버전 2.5으로 변경: Accept tuples as *prefix*.

str.strip([chars])

   Return a copy of the string with the leading and trailing
   characters removed. The *chars* argument is a string specifying the
   set of characters to be removed. If omitted or "None", the *chars*
   argument defaults to removing whitespace. The *chars* argument is
   not a prefix or suffix; rather, all combinations of its values are
   stripped:

   >>> '   spacious   '.strip()
   'spacious'
   >>> 'www.example.com'.strip('cmowz.')
   'example'

   버전 2.2.2으로 변경: Support for the *chars* argument.

str.swapcase()

   Return a copy of the string with uppercase characters converted to
   lowercase and vice versa.

   For 8-bit strings, this method is locale-dependent.

str.title()

   단어가 대문자로 시작하고 나머지 문자는 소문자가 되도록 문자열의 제
   목 케이스 버전을 돌려줍니다.

   이 알고리즘은 단어를 글자들의 연속으로 보는 간단한 언어 독립적 정의
   를 사용합니다. 이 정의는 여러 상황에서 작동하지만, 축약과 소유의 아
   포스트로피가 단어 경계를 형성한다는 것을 의미하고, 이는 원하는 결과
   가 아닐 수도 있습니다:

      >>> "they're bill's friends from the UK".title()
      "They'Re Bill'S Friends From The Uk"

   정규식을 사용하여 아포스트로피에 대한 해결 방법을 구성할 수 있습니
   다:

      >>> import re
      >>> def titlecase(s):
      ...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
      ...                   lambda mo: mo.group(0)[0].upper() +
      ...                              mo.group(0)[1:].lower(),
      ...                   s)
      ...
      >>> titlecase("they're bill's friends.")
      "They're Bill's Friends."

   For 8-bit strings, this method is locale-dependent.

str.translate(table[, deletechars])

   Return a copy of the string where all characters occurring in the
   optional argument *deletechars* are removed, and the remaining
   characters have been mapped through the given translation table,
   which must be a string of length 256.

   You can use the "maketrans()" helper function in the "string"
   module to create a translation table. For string objects, set the
   *table* argument to "None" for translations that only delete
   characters:

   >>> 'read this short text'.translate(None, 'aeiou')
   'rd ths shrt txt'

   버전 2.6에 추가: Support for a "None" *table* argument.

   For Unicode objects, the "translate()" method does not accept the
   optional *deletechars* argument.  Instead, it returns a copy of the
   *s* where all characters have been mapped through the given
   translation table which must be a mapping of Unicode ordinals to
   Unicode ordinals, Unicode strings or "None". Unmapped characters
   are left untouched. Characters mapped to "None" are deleted.  Note,
   a more flexible approach is to create a custom character mapping
   codec using the "codecs" module (see "encodings.cp1251" for an
   example).

str.upper()

   Return a copy of the string with all the cased characters [4]
   converted to uppercase.  Note that "s.upper().isupper()" might be
   "False" if "s" contains uncased characters or if the Unicode
   category of the resulting character(s) is not "Lu" (Letter,
   uppercase), but e.g. "Lt" (Letter, titlecase).

   For 8-bit strings, this method is locale-dependent.

str.zfill(width)

   Return the numeric string left filled with zeros in a string of
   length *width*.  A sign prefix is handled correctly.  The original
   string is returned if *width* is less than or equal to "len(s)".

   버전 2.2.2에 추가.

The following methods are present only on unicode objects:

unicode.isnumeric()

   Return "True" if there are only numeric characters in S, "False"
   otherwise. Numeric characters include digit characters, and all
   characters that have the Unicode numeric value property, e.g.
   U+2155, VULGAR FRACTION ONE FIFTH.

unicode.isdecimal()

   Return "True" if there are only decimal characters in S, "False"
   otherwise. Decimal characters include digit characters, and all
   characters that can be used to form decimal-radix numbers, e.g.
   U+0660, ARABIC-INDIC DIGIT ZERO.


5.6.2. String Formatting Operations
-----------------------------------

String and Unicode objects have one unique built-in operation: the "%"
operator (modulo).  This is also known as the string *formatting* or
*interpolation* operator.  Given "format % values" (where *format* is
a string or Unicode object), "%" conversion specifications in *format*
are replaced with zero or more elements of *values*.  The effect is
similar to the using "sprintf()" in the C language.  If *format* is a
Unicode object, or if any of the objects being converted using the
"%s" conversion are Unicode objects, the result will also be a Unicode
object.

*format* 이 하나의 인자를 요구하면, *values​​* 는 하나의 비 튜플 객체
일 수 있습니다. [5] 그렇지 않으면, *values​​* 는 format 문자열이 지정
하는 항목의 수와 같은 튜플이거나 단일 매핑 객체 (예를 들어, 딕셔너리)
이어야 합니다.

변환 명세는 두 개 이상의 문자를 포함하며 다음과 같은 구성 요소들을 포
함하는데, 반드시 이 순서대로 나와야 합니다:

1. "'%'" 문자: 명세의 시작을 나타냅니다.

2. 매핑 키 (선택 사항): 괄호로 둘러싸인 문자들의 시퀀스로 구성됩니
   다 ( 예를 들어, "(somename)").

3. 변환 플래그 (선택 사항): 일부 변환 유형의 결과에 영향을 줍니다.

4. 최소 필드 폭 (선택 사항): "'*'" (애스터리스크) 로 지정하면, 실제
   폭 은 *values* 튜플의 다음 요소에서 읽히고, 변환할 객체는 최소 필드
   폭 과 선택적 정밀도 뒤에 옵니다.

5. Precision (optional), given as a "'.'" (dot) followed by the
   precision.  If specified as "'*'" (an asterisk), the actual width
   is read from the next element of the tuple in *values*, and the
   value to convert comes after the precision.

6. 길이 수정자 (선택 사항).

7. 변환 유형.

오른쪽 인자가 딕셔너리 (또는 다른 매핑 형) 인 경우, 문자열에 있는 변환
명세는 *반드시* "'%'" 문자 바로 뒤에 그 딕셔너리의 매핑 키를 괄호로 둘
러싼 형태로 포함해야 합니다. 매핑 키는 포맷할 값을 매핑으로 부터 선택
합니다. 예를 들어:

>>> print '%(language)s has %(number)03d quote types.' % \
...       {"language": "Python", "number": 2}
Python has 002 quote types.

이 경우 "*" 지정자를 사용할 수 없습니다 (순차적인 파라미터 목록이 필요
하기 때문입니다).

변환 플래그 문자는 다음과 같습니다:

+-----------+-----------------------------------------------------------------------+
| 플래그    | 뜻                                                                    |
+===========+=======================================================================+
| "'#'"     | 값 변환에 "대체 형식" (아래에 정의되어있습니다) 을 사용합니다.        |
+-----------+-----------------------------------------------------------------------+
| "'0'"     | 변환은 숫자 값의 경우 0으로 채웁니다.                                 |
+-----------+-----------------------------------------------------------------------+
| "'-'"     | 변환된 값은 왼쪽으로 정렬됩니다 (둘 다 주어지면 "'0'" 변환보다 우선   |
|           | 합 니다).                                                             |
+-----------+-----------------------------------------------------------------------+
| "' '"     | (스페이스) 부호 있는 변환 때문에 만들어진 양수 앞에 빈칸을 남겨둡니다 |
|           | (음수면 빈 문자열입니다).                                             |
+-----------+-----------------------------------------------------------------------+
| "'+'"     | 부호 문자 ("'+'" or "'-'") 가 변환 앞에 놓입니다 ("' '" 플래그에 우선 |
|           | 합니다).                                                              |
+-----------+-----------------------------------------------------------------------+

길이 수정자 ("h", "l", "L") 를 제공할 수는 있지만, 파이썬에서 필요하지
않기 때문에 무시됩니다 -- 예를 들어 "%ld" 는 "%d" 와 같습니다.

변환 유형은 다음과 같습니다:

+--------------+-------------------------------------------------------+---------+
| 변환         | 뜻                                                    | 노트    |
+==============+=======================================================+=========+
| "'d'"        | 부호 있는 정수 십진 표기.                             |         |
+--------------+-------------------------------------------------------+---------+
| "'i'"        | 부호 있는 정수 십진 표기.                             |         |
+--------------+-------------------------------------------------------+---------+
| "'o'"        | 부호 있는 8진수 값.                                   | (1)     |
+--------------+-------------------------------------------------------+---------+
| "'u'"        | 쓸데없는 유형 -- "'d'" 와 같습니다.                   | (7)     |
+--------------+-------------------------------------------------------+---------+
| "'x'"        | 부호 있는 16진수 (소문자).                            | (2)     |
+--------------+-------------------------------------------------------+---------+
| "'X'"        | 부호 있는 16진수 (대문자).                            | (2)     |
+--------------+-------------------------------------------------------+---------+
| "'e'"        | 부동 소수점 지수 형식 (소문자).                       | (3)     |
+--------------+-------------------------------------------------------+---------+
| "'E'"        | 부동 소수점 지수 형식 (대문자).                       | (3)     |
+--------------+-------------------------------------------------------+---------+
| "'f'"        | 부동 소수점 십진수 형식.                              | (3)     |
+--------------+-------------------------------------------------------+---------+
| "'F'"        | 부동 소수점 십진수 형식.                              | (3)     |
+--------------+-------------------------------------------------------+---------+
| "'g'"        | 부동 소수점 형식. 지수가 -4보다 작거나 정밀도 보다 작 | (4)     |
|              | 지 않으면 소문자 지수형식을 사용하고, 그렇지 않으면   |         |
|              | 십진수 형식을 사용합니다.                             |         |
+--------------+-------------------------------------------------------+---------+
| "'G'"        | 부동 소수점 형식. 지수가 -4보다 작거나 정밀도 보다 작 | (4)     |
|              | 지 않으면 대문자 지수형식을 사용하고, 그렇지 않으면   |         |
|              | 십진수 형식을 사용합니다.                             |         |
+--------------+-------------------------------------------------------+---------+
| "'c'"        | 단일 문자 (정수 또는 길이 1인 문자열을 허용합니다).   |         |
+--------------+-------------------------------------------------------+---------+
| "'r'"        | String (converts any Python object using repr()).     | (5)     |
+--------------+-------------------------------------------------------+---------+
| "'s'"        | 문자열 ("str()" 을 사용하여 파이썬 객체를 변환합니다  | (6)     |
|              | ).                                                    |         |
+--------------+-------------------------------------------------------+---------+
| "'%'"        | 인자는 변환되지 않고, 결과에 "'%'" 문자가 표시됩니다. |         |
+--------------+-------------------------------------------------------+---------+

노트:

1. The alternate form causes a leading zero ("'0'") to be inserted
   between left-hand padding and the formatting of the number if the
   leading character of the result is not already a zero.

2. 대체 형식은 첫 번째 숫자 앞에 선행 "'0x'" 또는 "'0X'" ("'x'" 나
   "'X'" 유형 중 어느 것을 사용하느냐에 따라 달라집니다) 를 삽입합니다
   .

3. 대체 형식은 그 뒤에 숫자가 나오지 않더라도 항상 소수점을 포함합
   니다 .

   정밀도는 소수점 이하 자릿수를 결정하며 기본값은 6입니다.

4. 대체 형식은 결과에 항상 소수점을 포함하고 뒤에 오는 0은 제거되지
   않 습니다.

   정밀도는 소수점 앞뒤의 유효 자릿수를 결정하며 기본값은 6입니다.

5. The "%r" conversion was added in Python 2.0.

   The precision determines the maximal number of characters used.

6. If the object or format provided is a "unicode" string, the
   resulting string will also be "unicode".

   The precision determines the maximal number of characters used.

7. **PEP 237**을 참조하세요.

파이썬 문자열은 명시적인 길이를 가지고 있으므로, "%s" 변환은 문자열의
끝이 "'\0'" 이라고 가정하지 않습니다.

버전 2.7으로 변경: 절댓값이 1e50 을 넘는 숫자에 대한 "%f" 변환은 더는
"%g" 변환으로 대체되지 않습니다.

Additional string operations are defined in standard modules "string"
and "re".


5.6.3. XRange Type
------------------

The "xrange" type is an immutable sequence which is commonly used for
looping.  The advantage of the "xrange" type is that an "xrange"
object will always take the same amount of memory, no matter the size
of the range it represents.  There are no consistent performance
advantages.

XRange objects have very little behavior: they only support indexing,
iteration, and the "len()" function.


5.6.4. 가변 시퀀스 형
---------------------

List and "bytearray" objects support additional operations that allow
in-place modification of the object. Other mutable sequence types
(when added to the language) should also support these operations.
Strings and tuples are immutable sequence types: such objects cannot
be modified once created. The following operations are defined on
mutable sequence types (where *x* is an arbitrary object):

+--------------------------------+----------------------------------+-----------------------+
| 연산                           | 결과                             | 노트                  |
+================================+==================================+=======================+
| "s[i] = x"                     | *s* 의 항목 *i* 를 *x* 로 대체합 |                       |
|                                | 니다                             |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s[i:j] = t"                   | *i* 에서 *j* 까지의 *s* 슬라이스 |                       |
|                                | 가 이터러블 *t* 의 내용으로 대체 |                       |
|                                | 됩니다                           |                       |
+--------------------------------+----------------------------------+-----------------------+
| "del s[i:j]"                   | "s[i:j] = []" 와 같습니다        |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s[i:j:k] = t"                 | "s[i:j:k]" 의 항목들이 *t* 의 항 | (1)                   |
|                                | 목들로 대체됩니다                |                       |
+--------------------------------+----------------------------------+-----------------------+
| "del s[i:j:k]"                 | 리스트에서 "s[i:j:k]" 의 항목들  |                       |
|                                | 을 제거합니다                    |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.append(x)"                  | same as "s[len(s):len(s)] = [x]" | (2)                   |
+--------------------------------+----------------------------------+-----------------------+
| "s.extend(t)" 또는 "s += t"    | for the most part the same as    | (3)                   |
|                                | "s[len(s):len(s)] = t"           |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s *= n"                       | 내용이 *n* 번 반복되도록 *s* 를  | (11)                  |
|                                | 갱신합니다                       |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.count(x)"                   | return number of *i*'s for which |                       |
|                                | "s[i] == x"                      |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.index(x[, i[, j]])"         | return smallest *k* such that    | (4)                   |
|                                | "s[k] == x" and "i <= k < j"     |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.insert(i, x)"               | same as "s[i:i] = [x]"           | (5)                   |
+--------------------------------+----------------------------------+-----------------------+
| "s.pop([i])"                   | same as "x = s[i]; del s[i];     | (6)                   |
|                                | return x"                        |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.remove(x)"                  | same as "del s[s.index(x)]"      | (4)                   |
+--------------------------------+----------------------------------+-----------------------+
| "s.reverse()"                  | 제자리에서 *s* 의 항목들의 순서  | (7)                   |
|                                | 를 뒤집습니다                    |                       |
+--------------------------------+----------------------------------+-----------------------+
| "s.sort([cmp[, key[,           | sort the items of *s* in place   | (7)(8)(9)(10)         |
| reverse]]])"                   |                                  |                       |
+--------------------------------+----------------------------------+-----------------------+

노트:

1. *t* must have the same length as the slice it is  replacing.

2. The C implementation of Python has historically accepted
   multiple parameters and implicitly joined them into a tuple; this
   no longer works in Python 2.0.  Use of this misfeature has been
   deprecated since Python 1.4.

3. *t* can be any iterable object.

4. Raises "ValueError" when *x* is not found in *s*. When a
   negative index is passed as the second or third parameter to the
   "index()" method, the list length is added, as for slice indices.
   If it is still negative, it is truncated to zero, as for slice
   indices.

   버전 2.3으로 변경: Previously, "index()" didn't have arguments for
   specifying start and stop positions.

5. When a negative index is passed as the first parameter to the
   "insert()" method, the list length is added, as for slice indices.
   If it is still negative, it is truncated to zero, as for slice
   indices.

   버전 2.3으로 변경: Previously, all negative indices were truncated
   to zero.

6. The "pop()" method's optional argument *i* defaults to "-1", so
   that by default the last item is removed and returned.

7. The "sort()" and "reverse()" methods modify the list in place
   for economy of space when sorting or reversing a large list.  To
   remind you that they operate by side effect, they don't return the
   sorted or reversed list.

8. The "sort()" method takes optional arguments for controlling the
   comparisons.

   *cmp* specifies a custom comparison function of two arguments (list
   items) which should return a negative, zero or positive number
   depending on whether the first argument is considered smaller than,
   equal to, or larger than the second argument: "cmp=lambda x,y:
   cmp(x.lower(), y.lower())".  The default value is "None".

   *key* specifies a function of one argument that is used to extract
   a comparison key from each list element: "key=str.lower".  The
   default value is "None".

   *reverse* 는 논리값입니다. "True" 로 설정되면, 각 비교가 역전된 것
   처럼 리스트 요소들이 정렬됩니다.

   In general, the *key* and *reverse* conversion processes are much
   faster than specifying an equivalent *cmp* function.  This is
   because *cmp* is called multiple times for each list element while
   *key* and *reverse* touch each element only once.  Use
   "functools.cmp_to_key()" to convert an old-style *cmp* function to
   a *key* function.

   버전 2.3으로 변경: Support for "None" as an equivalent to omitting
   *cmp* was added.

   버전 2.4으로 변경: Support for *key* and *reverse* was added.

9. Starting with Python 2.3, the "sort()" method is guaranteed to
   be stable.  A sort is stable if it guarantees not to change the
   relative order of elements that compare equal --- this is helpful
   for sorting in multiple passes (for example, sort by department,
   then by salary grade).

10. **CPython implementation detail:** While a list is being
    sorted, the effect of attempting to mutate, or even inspect, the
    list is undefined.  The C implementation of Python 2.3 and newer
    makes the list appear empty for the duration, and raises
    "ValueError" if it can detect that the list has been mutated
    during a sort.

11. The value *n* is an integer, or an object implementing
    "__index__()".  Zero and negative values of *n* clear the
    sequence.  Items in the sequence are not copied; they are
    referenced multiple times, as explained for "s * n" under Sequence
    Types --- str, unicode, list, tuple, bytearray, buffer, xrange.


5.7. 집합 형 --- "set", "frozenset"
===================================

A *set* object is an unordered collection of distinct *hashable*
objects. Common uses include membership testing, removing duplicates
from a sequence, and computing mathematical operations such as
intersection, union, difference, and symmetric difference. (For other
containers see the built in "dict", "list", and "tuple" classes, and
the "collections" module.)

버전 2.4에 추가.

다른 컬렉션과 마찬가지로, 집합은 "x in set",``len(set)``, "for x in
set" 을 지원합니다. 순서가 없는 컬렉션이므로, 집합은 원소의 위치나 삽
입 순서를 기록하지 않습니다. 따라서 집합은 인덱싱, 슬라이싱 또는 기타
시퀀스와 유사한 동작을 지원하지 않습니다.

현재 두 가지 내장형이 있습니다, "set"과 "frozenset". "set" 형은 가변입
니다 --- 내용을 "add()" 나 "remove()" 와 같은 메서드를 사용하여 변경할
수 있습니다. 가변이기 때문에, 해시값이 없으며 딕셔너리 키 또는 다른 집
합의 원소로 사용할 수 없습니다. "frozenset" 형은 불변이고 *해시 가능*
합니다 --- 만들어진 후에는 내용을 바꿀 수 없습니다; 따라서 딕셔너리 키
또는 다른 집합의 원소로 사용할 수 있습니다.

As of Python 2.7, non-empty sets (not frozensets) can be created by
placing a comma-separated list of elements within braces, for example:
"{'jack', 'sjoerd'}", in addition to the "set" constructor.

두 클래스의 생성자는 같게 작동합니다:

class set([iterable])
class frozenset([iterable])

   *iterable* 에서 요소를 취하는 새 set 또는 frozenset 객체를 돌려줍니
   다. 집합의 원소는 반드시 *해시 가능* 해야 합니다. 집합의 집합을 표
   현하려면, 포함되는 집합은 반드시 "frozenset" 객체여야 합니다.
   *iterable* 을 지정하지 않으면 새 빈 집합을 돌려줍니다.

   "set"과 "frozenset" 의 인스턴스는 다음과 같은 연산을 제공합니다:

   len(s)

      집합 *s* 의 원소 수(*s* 의 크기)를 돌려줍니다.

   x in s

      *s* 에 대해 *x* 의 멤버십을 검사합니다.

   x not in s

      *s* 에 대해 *x* 의 비 멤버십을 검사합니다.

   isdisjoint(other)

      집합이 *other* 와 공통 원소를 갖지 않는 경우 "True" 을 돌려줍니
      다. 집합은 교집합이 공집합일 때, 그리고 그때만 서로소(disjoint)
      라고 합니다.

      버전 2.6에 추가.

   issubset(other)
   set <= other

      집합의 모든 원소가 *other* 에 포함되는지 검사합니다.

   set < other

      집합이 *other* 의 진부분집합인지 검사합니다, 즉, "set <= other
      and set != other".

   issuperset(other)
   set >= other

      *other* 의 모든 원소가 집합에 포함되는지 검사합니다.

   set > other

      집합이 *other* 의 진상위집합인지 검사합니다, 즉, "set >= other
      and set != other".

   union(*others)
   set | other | ...

      집합과 모든 others에 있는 원소들로 구성된 새 집합을 돌려줍니다.

      버전 2.6으로 변경: Accepts multiple input iterables.

   intersection(*others)
   set & other & ...

      집합과 모든 others의 공통 원소들로 구성된 새 집합을 돌려줍니다.

      버전 2.6으로 변경: Accepts multiple input iterables.

   difference(*others)
   set - other - ...

      집합에는 포함되었으나 others에는 포함되지 않은 원소들로 구성된
      새 집합을 돌려줍니다.

      버전 2.6으로 변경: Accepts multiple input iterables.

   symmetric_difference(other)
   set ^ other

      집합이나 other에 포함되어 있으나 둘 모두에 포함되지는 않은 원소
      들로 구성된 새 집합을 돌려줍니다.

   copy()

      Return a shallow copy of the set.

   참고로, 연산자가 아닌 버전의 "union()", "intersection()",
   "difference()", "symmetric_difference()", "issubset()",
   "issuperset()" 메서드는 임의의 이터러블을 인자로 받아들입니다. 대조
   적으로, 연산자를 기반으로 하는 대응 연산들은 인자가 집합일 것을 요
   구합니다. 이것은 오류가 발생하기 쉬운 "set('abc') & 'cbs'" 와 같은
   구성을 배제하고 더 읽기 쉬운 "set('abc').intersection('cbs')" 를 선
   호합니다.

   "set"과 "frozenset" 모두 집합 간의 비교를 지원합니다. 두 집합은 각
   집합의 모든 원소가 다른 집합에 포함되어있는 경우에만 같습니다 (서로
   다른 집합의 부분집합입니다). 집합이 다른 집합의 진부분집합(부분집합
   이지만 같지는 않은 경우)일 때만 첫 번째 집합이 두 번째 집합보다 작
   습니다. 집합이 다른 집합의 진상위집합(상위집합이지만 같지는 않은 경
   우)일 때만 첫 번째 집합이 두 번째 집합보다 큽니다.

   "set" 의 인스턴스는 그 원소를 기반으로 "frozenset" 의 인스턴스와 비
   교됩니다. 예를 들어, "set('abc') == frozenset('abc')" 는 "True" 를
   돌려주고 "set('abc') in set([frozenset('abc')])" 도 마찬가지입니다.

   The subset and equality comparisons do not generalize to a total
   ordering function.  For example, any two non-empty disjoint sets
   are not equal and are not subsets of each other, so *all* of the
   following return "False": "a<b", "a==b", or "a>b". Accordingly,
   sets do not implement the "__cmp__()" method.

   집합은 부분 순서(부분 집합 관계)만 정의하기 때문에, 집합의 리스트에
   대한 "list.sort()" 메서드의 결과는 정의되지 않습니다.

   딕셔너리 키처럼, 집합의 원소는 반드시 *해시 가능* 해야 합니다.

   "set" 인스턴스와 "frozenset" 을 혼합 한 이항 연산은 첫 번째 피연산
   자의 형을 돌려줍니다. 예를 들어: "frozenset('ab') | set('bc')" 는
   "frozenset" 의 인스턴스를 돌려줍니다.

   다음 표는 "frozenset" 의 불변 인스턴스에는 적용되지 않고 "set" 에서
   만 사용할 수 있는 연산들을 나열합니다:

   update(*others)
   set |= other | ...

      집합을 갱신해서, 모든 others의 원소들을 더합니다.

      버전 2.6으로 변경: Accepts multiple input iterables.

   intersection_update(*others)
   set &= other & ...

      집합을 갱신해서, 그 집합과 others에 공통으로 포함된 원소들만 남
      깁니다.

      버전 2.6으로 변경: Accepts multiple input iterables.

   difference_update(*others)
   set -= other | ...

      집합을 갱신해서, others에 있는 원소들을 제거합니다.

      버전 2.6으로 변경: Accepts multiple input iterables.

   symmetric_difference_update(other)
   set ^= other

      집합을 갱신해서, 두 집합의 어느 한 곳에만 포함된 원소들만 남깁니
      다.

   add(elem)

      원소 *elem* 을 집합에 추가합니다.

   remove(elem)

      원소 *elem* 을 집합에서 제거합니다. *elem* 가 집합에 포함되어 있
      지 않으면 "KeyError" 를 일으킵니다.

   discard(elem)

      원소 *elem* 이 집합에 포함되어 있으면 제거합니다.

   pop()

      집합으로부터 임의의 원소를 제거해 돌려줍니다. 집합이 비어있는 경
      우 "KeyError" 를 일으킵니다.

   clear()

      집합의 모든 원소를 제거합니다.

   참고로, "update()", "intersection_update()", "difference_update()",
   "symmetric_difference_update()" 메서드의 비 연산자 버전은 임의의 이
   터러블을 인자로 받아들입니다.

   참고로, "__contains__()", "remove()", "discard()" 메서드로 제공되는
   *elem* 인자는 set 일 수 있습니다. 동등한 frozenset 검색을 지원하기
   위해, *elem* 으로 임시 frozenset 을 만듭니다.

더 보기:

  Comparison to the built-in set types
     Differences between the "sets" module and the built-in set types.


5.8. 매핑 형 --- "dict"
=======================

A *mapping* object maps *hashable* values to arbitrary objects.
Mappings are mutable objects.  There is currently only one standard
mapping type, the *dictionary*.  (For other containers see the built
in "list", "set", and "tuple" classes, and the "collections" module.)

딕셔너리의 키는 *거의* 임의의 값입니다. *해시 가능* 하지 않은 값들, 즉
, 리스트, 딕셔너리 또는 다른 가변형 (객체 아이덴티티 대신 값으로 비교
됩니다) 은 키로 사용할 수 없습니다. 키에 사용되는 숫자 형은 숫자 비교
를 위한 일반적인 규칙을 따릅니다: 두 숫자가 같다고 비교되는 경우 ("1"
과 "1.0" 처럼) 같은 딕셔너리 항목을 인덱싱하는데 서로 교환하여 사용할
수 있습니다. (그러나 컴퓨터는 부동 소수점 숫자를 근삿값으로 저장하므로
이것들을 딕셔너리 키로 사용하는 것은 현명하지 않습니다.)

딕셔너리는 "dict" 생성자뿐만 아니라 중괄호 안에 쉼표로 구분된 "key:
value" 쌍을 나열해서 만들 수 있습니다, 예를 들어: "{'jack': 4098,
'sjoerd': 4127}" 또는 "{4098: 'jack', 4127: 'sjoerd'}".

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

   선택적 위치 인자와 (비어있을 수 있는) 키워드 인자들의 집합으로부터
   초기화된 새 딕셔너리를 돌려줍니다.

   위치 인자가 제공되지 않으면 빈 딕셔너리가 만들어집니다. 위치 인자가
   지정되고 매핑 객체인 경우, 매핑 객체와 같은 키-값 쌍을 갖는 딕셔너
   리가 만들어집니다. 그렇지 않으면, 위치 인자는 *이터러블* 객체여야
   합니다. 이터러블의 각 항목은 그 자체로 정확하게 두 개의 객체가 있는
   이터러블이어야 합니다. 각 항목의 첫 번째 객체는 새 딕셔너리의 키가
   되고, 두 ​​번째 객체는 해당 값이 됩니다. 키가 두 번 이상 나타나면,
   그 키의 마지막 값이 새 딕셔너리의 해당 값이 됩니다.

   키워드 인자가 제공되면, 키워드 인자와 해당 값이 위치 인자로부터 만
   들어진 딕셔너리에 추가됩니다. 추가되는 키가 이미 존재하면, 키워드
   인자에서 온 값이 위치 인자에게서 온 값을 대체합니다.

   예를 들어, 다음 예제는 모두 "{"one": 1, "two": 2, "three": 3}" 와
   같은 딕셔너리를 돌려줍니다:

      >>> a = dict(one=1, two=2, three=3)
      >>> b = {'one': 1, 'two': 2, 'three': 3}
      >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
      >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
      >>> e = dict({'three': 3, 'one': 1, 'two': 2})
      >>> a == b == c == d == e
      True

   첫 번째 예제에서와같이 키워드 인자는 유효한 파이썬 식별자인 키에 대
   해서만 작동합니다. 그 외의 경우는 모든 유효한 키를 사용할 수 있습니
   다.

   버전 2.2에 추가.

   버전 2.3으로 변경: Support for building a dictionary from keyword
   arguments added.

   이것들은 딕셔너리가 지원하는 연산들입니다 (그러므로, 사용자 정의 매
   핑 형도 지원해야 합니다):

   len(d)

      딕셔너리 *d* 에 있는 항목의 수를 돌려줍니다.

   d[key]

      키 *key* 인 *d* 의 항목을 돌려줍니다. *key* 가 매핑에 없는 경우
      "KeyError" 를 일으킵니다.

      dict 의 서브 클래스가 method "__missing__()" 을 정의하고 *key*
      가 존재하지 않는다면, "d[key]" 연산은 키 *key* 를 인자로 하여 그
      메서드를 호출합니다. 그런 다음 "d[key]" 연산은
      "__missing__(key)" 호출이 반환한 값이나 일으킨 예외를 그대로 반
      환하거나 일으킵니다. 다른 연산이나 메서드는 "__missing__()" 을
      호출하지 않습니다. "__missing__()" 이 정의되어 있지 않으면
      "KeyError" 를 일으킵니다. "__missing__()" 은 메서드 여야 합니다;
      인스턴스 변수가 될 수 없습니다:

         >>> class Counter(dict):
         ...     def __missing__(self, key):
         ...         return 0
         >>> c = Counter()
         >>> c['red']
         0
         >>> c['red'] += 1
         >>> c['red']
         1

      위의 예는 "collections.Counter" 구현 일부를 보여줍니다. 다른
      "__missing__" 메서드가 "collections.defaultdict" 에서 사용됩니다
      .

      버전 2.5에 추가: Recognition of __missing__ methods of dict
      subclasses.

   d[key] = value

      "d[key]" 를 *value* 로 설정합니다.

   del d[key]

      *d* 에서 "d[key]" 를 제거합니다. *key* 가 매핑에 없는 경우
      "KeyError" 를 일으킵니다.

   key in d

      *d* 에 키 *key* 가 있으면 "True" 를, 그렇지 않으면 "False" 를 돌
      려줍니다.

      버전 2.2에 추가.

   key not in d

      "not key in d" 와 동등합니다.

      버전 2.2에 추가.

   iter(d)

      Return an iterator over the keys of the dictionary.  This is a
      shortcut for "iterkeys()".

   clear()

      딕셔너리에서 모든 항목을 제거합니다.

   copy()

      딕셔너리의 얕은 복사본을 돌려줍니다.

   fromkeys(seq[, value])

      *seq* 가 제공하는 값들을 키로 사용하고 모든 값을 *value* 로 설정
      한 새 딕셔러리를 돌려줍니다.

      "fromkeys()" is a class method that returns a new dictionary.
      *value* defaults to "None".

      버전 2.3에 추가.

   get(key[, default])

      *key* 가 딕셔너리에 있는 경우 *key* 에 대응하는 값을 돌려주고,
      그렇지 않으면 *default* 를 돌려줍니다. *default* 가 주어지지 않
      으면 기본값 "None" 이 사용됩니다. 그래서 이 메서드는 절대로
      "KeyError" 를 일으키지 않습니다.

   has_key(key)

      Test for the presence of *key* in the dictionary.  "has_key()"
      is deprecated in favor of "key in d".

   items()

      Return a copy of the dictionary's list of "(key, value)" pairs.

      **CPython implementation detail:** Keys and values are listed in
      an arbitrary order which is non-random, varies across Python
      implementations, and depends on the dictionary's history of
      insertions and deletions.

      If "items()", "keys()", "values()", "iteritems()", "iterkeys()",
      and "itervalues()" are called with no intervening modifications
      to the dictionary, the lists will directly correspond.  This
      allows the creation of "(value, key)" pairs using "zip()":
      "pairs = zip(d.values(), d.keys())".  The same relationship
      holds for the "iterkeys()" and "itervalues()" methods: "pairs =
      zip(d.itervalues(), d.iterkeys())" provides the same value for
      "pairs". Another way to create the same list is "pairs = [(v, k)
      for (k, v) in d.iteritems()]".

   iteritems()

      Return an iterator over the dictionary's "(key, value)" pairs.
      See the note for "dict.items()".

      Using "iteritems()" while adding or deleting entries in the
      dictionary may raise a "RuntimeError" or fail to iterate over
      all entries.

      버전 2.2에 추가.

   iterkeys()

      Return an iterator over the dictionary's keys.  See the note for
      "dict.items()".

      Using "iterkeys()" while adding or deleting entries in the
      dictionary may raise a "RuntimeError" or fail to iterate over
      all entries.

      버전 2.2에 추가.

   itervalues()

      Return an iterator over the dictionary's values.  See the note
      for "dict.items()".

      Using "itervalues()" while adding or deleting entries in the
      dictionary may raise a "RuntimeError" or fail to iterate over
      all entries.

      버전 2.2에 추가.

   keys()

      Return a copy of the dictionary's list of keys.  See the note
      for "dict.items()".

   pop(key[, default])

      *key* 가 딕셔너리에 있으면 제거하고 그 값을 돌려줍니다. 그렇지
      않으면 *default* 를 돌려줍니다. *default* 가 주어지지 않고 *key*
      가 딕셔너리에 없으면 "KeyError" 를 일으킵니다.

      버전 2.3에 추가.

   popitem()

      딕셔너리에서 임의의 "(key, value)" 쌍을 제거하고 돌려줍니다.

      "popitem()" is useful to destructively iterate over a
      dictionary, as often used in set algorithms.  If the dictionary
      is empty, calling "popitem()" raises a "KeyError".

   setdefault(key[, default])

      *key* 가 딕셔너리에 있으면 해당 값을 돌려줍니다. 그렇지 않으면,
      *default* 값을 갖는 *key* 를 삽입한 후 *default* 를 돌려줍니다.
      *default* 의 기본값은 "None" 입니다.

   update([other])

      *other* 가 제공하는 키/값 쌍으로 사전을 갱신합니다. 기존 키는 덮
      어씁니다. "None" 을 돌려줍니다.

      "update()" accepts either another dictionary object or an
      iterable of key/value pairs (as tuples or other iterables of
      length two).  If keyword arguments are specified, the dictionary
      is then updated with those key/value pairs: "d.update(red=1,
      blue=2)".

      버전 2.4으로 변경: Allowed the argument to be an iterable of
      key/value pairs and allowed keyword arguments.

   values()

      Return a copy of the dictionary's list of values.  See the note
      for "dict.items()".

   viewitems()

      Return a new view of the dictionary's items ("(key, value)"
      pairs).  See below for documentation of view objects.

      버전 2.7에 추가.

   viewkeys()

      Return a new view of the dictionary's keys.  See below for
      documentation of view objects.

      버전 2.7에 추가.

   viewvalues()

      Return a new view of the dictionary's values.  See below for
      documentation of view objects.

      버전 2.7에 추가.

   Dictionaries compare equal if and only if they have the same "(key,
   value)" pairs.


5.8.1. 딕셔너리 뷰 객체
-----------------------

The objects returned by "dict.viewkeys()", "dict.viewvalues()" and
"dict.viewitems()" are *view objects*.  They provide a dynamic view on
the dictionary's entries, which means that when the dictionary
changes, the view reflects these changes.

딕셔너리 뷰는 이터레이션을 통해 각각의 데이터를 산출할 수 있고, 멤버십
검사를 지원합니다:

len(dictview)

   딕셔너리에 있는 항목 수를 돌려줍니다.

iter(dictview)

   딕셔너리에서 키, 값, 항목("(key, value)" 튜플로 표현됩니다)에 대한
   이터레이터를 돌려줍니다.

   키와 값은 무작위는 아니지만, 임의의 순서(파이썬 구현에 따라 달라집
   니다)로 이터레이션 되고, 딕셔너리의 삽입 및 삭제 이력에 따라 달라집
   니다. 키, 값 및 항목 뷰를 이터레이션 하는 도중에 딕셔너리를 수정하
   지 않으면, 항목들의 순서는 모두 일치합니다. 이 때문에 "zip()"을 사
   용해서 "(value, key)" 쌍을 만들 수 있습니다: "pairs =
   zip(d.values(), d.keys())". 같은 리스트를 만드는 다른 방법은 "pairs
   = [(v, k) for (k, v) in d.items()]" 입니다.

   딕셔너리에 항목을 추가하거나 삭제하는 동안 뷰를 이터레이션 하면
   "RuntimeError" 를 일으키거나 모든 항목을 이터레이션 하지 못할 수 있
   습니다.

x in dictview

   *x* 가 하부 딕셔너리의 키, 갑, 항목에 있는 경우 "True" 를 돌려줍니
   다 (마지막의 경우 *x* 는 "(key, value)" 튜플이어야 합니다).

Keys views are set-like since their entries are unique and hashable.
If all values are hashable, so that (key, value) pairs are unique and
hashable, then the items view is also set-like.  (Values views are not
treated as set-like since the entries are generally not unique.)  Then
these set operations are available ("other" refers either to another
view or a set):

dictview & other

   Return the intersection of the dictview and the other object as a
   new set.

dictview | other

   Return the union of the dictview and the other object as a new set.

dictview - other

   Return the difference between the dictview and the other object
   (all elements in *dictview* that aren't in *other*) as a new set.

dictview ^ other

   Return the symmetric difference (all elements either in *dictview*
   or *other*, but not in both) of the dictview and the other object
   as a new set.

딕셔너리 뷰 사용의 예:

   >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
   >>> keys = dishes.viewkeys()
   >>> values = dishes.viewvalues()

   >>> # iteration
   >>> n = 0
   >>> for val in values:
   ...     n += val
   >>> print(n)
   504

   >>> # keys and values are iterated over in the same order
   >>> list(keys)
   ['eggs', 'bacon', 'sausage', 'spam']
   >>> list(values)
   [2, 1, 1, 500]

   >>> # view objects are dynamic and reflect dict changes
   >>> del dishes['eggs']
   >>> del dishes['sausage']
   >>> list(keys)
   ['spam', 'bacon']

   >>> # set operations
   >>> keys & {'eggs', 'bacon', 'salad'}
   {'bacon'}


5.9. File Objects
=================

File objects are implemented using C's "stdio" package and can be
created with the built-in "open()" function.  File objects are also
returned by some other built-in functions and methods, such as
"os.popen()" and "os.fdopen()" and the "makefile()" method of socket
objects. Temporary files can be created using the "tempfile" module,
and high-level file operations such as copying, moving, and deleting
files and directories can be achieved with the "shutil" module.

When a file operation fails for an I/O-related reason, the exception
"IOError" is raised.  This includes situations where the operation is
not defined for some reason, like "seek()" on a tty device or writing
a file opened for reading.

Files have the following methods:

file.close()

   Close the file.  A closed file cannot be read or written any more.
   Any operation which requires that the file be open will raise a
   "ValueError" after the file has been closed.  Calling "close()"
   more than once is allowed.

   As of Python 2.5, you can avoid having to call this method
   explicitly if you use the "with" statement.  For example, the
   following code will automatically close *f* when the "with" block
   is exited:

      from __future__ import with_statement # This isn't required in Python 2.6

      with open("hello.txt") as f:
          for line in f:
              print line,

   In older versions of Python, you would have needed to do this to
   get the same effect:

      f = open("hello.txt")
      try:
          for line in f:
              print line,
      finally:
          f.close()

   주석: Not all "file-like" types in Python support use as a
     context manager for the "with" statement.  If your code is
     intended to work with any file-like object, you can use the
     function "contextlib.closing()" instead of using the object
     directly.

file.flush()

   Flush the internal buffer, like "stdio"'s "fflush()".  This may be
   a no-op on some file-like objects.

   주석: "flush()" does not necessarily write the file's data to
     disk. Use "flush()" followed by "os.fsync()" to ensure this
     behavior.

file.fileno()

   Return the integer "file descriptor" that is used by the underlying
   implementation to request I/O operations from the operating system.
   This can be useful for other, lower level interfaces that use file
   descriptors, such as the "fcntl" module or "os.read()" and friends.

   주석: File-like objects which do not have a real file descriptor
     should *not* provide this method!

file.isatty()

   Return "True" if the file is connected to a tty(-like) device, else
   "False".

   주석: If a file-like object is not associated with a real file,
     this method should *not* be implemented.

file.next()

   A file object is its own iterator, for example "iter(f)" returns
   *f* (unless *f* is closed).  When a file is used as an iterator,
   typically in a "for" loop (for example, "for line in f: print
   line.strip()"), the "next()" method is called repeatedly.  This
   method returns the next input line, or raises "StopIteration" when
   EOF is hit when the file is open for reading (behavior is undefined
   when the file is open for writing).  In order to make a "for" loop
   the most efficient way of looping over the lines of a file (a very
   common operation), the "next()" method uses a hidden read-ahead
   buffer.  As a consequence of using a read-ahead buffer, combining
   "next()" with other file methods (like "readline()") does not work
   right.  However, using "seek()" to reposition the file to an
   absolute position will flush the read-ahead buffer.

   버전 2.3에 추가.

file.read([size])

   Read at most *size* bytes from the file (less if the read hits EOF
   before obtaining *size* bytes).  If the *size* argument is negative
   or omitted, read all data until EOF is reached.  The bytes are
   returned as a string object.  An empty string is returned when EOF
   is encountered immediately.  (For certain files, like ttys, it
   makes sense to continue reading after an EOF is hit.)  Note that
   this method may call the underlying C function "fread()" more than
   once in an effort to acquire as close to *size* bytes as possible.
   Also note that when in non-blocking mode, less data than was
   requested may be returned, even if no *size* parameter was given.

   주석: This function is simply a wrapper for the underlying
     "fread()" C function, and will behave the same in corner cases,
     such as whether the EOF value is cached.

file.readline([size])

   Read one entire line from the file.  A trailing newline character
   is kept in the string (but may be absent when a file ends with an
   incomplete line). [6] If the *size* argument is present and non-
   negative, it is a maximum byte count (including the trailing
   newline) and an incomplete line may be returned. When *size* is not
   0, an empty string is returned *only* when EOF is encountered
   immediately.

   주석: Unlike "stdio"'s "fgets()", the returned string contains
     null characters ("'\0'") if they occurred in the input.

file.readlines([sizehint])

   Read until EOF using "readline()" and return a list containing the
   lines thus read.  If the optional *sizehint* argument is present,
   instead of reading up to EOF, whole lines totalling approximately
   *sizehint* bytes (possibly after rounding up to an internal buffer
   size) are read.  Objects implementing a file-like interface may
   choose to ignore *sizehint* if it cannot be implemented, or cannot
   be implemented efficiently.

file.xreadlines()

   This method returns the same thing as "iter(f)".

   버전 2.1에 추가.

   버전 2.3 폐지: Use "for line in file" instead.

file.seek(offset[, whence])

   Set the file's current position, like "stdio"'s "fseek()". The
   *whence* argument is optional and defaults to  "os.SEEK_SET" or "0"
   (absolute file positioning); other values are "os.SEEK_CUR" or "1"
   (seek relative to the current position) and "os.SEEK_END" or "2"
   (seek relative to the file's end).  There is no return value.

   For example, "f.seek(2, os.SEEK_CUR)" advances the position by two
   and "f.seek(-3, os.SEEK_END)" sets the position to the third to
   last.

   Note that if the file is opened for appending (mode "'a'" or
   "'a+'"), any "seek()" operations will be undone at the next write.
   If the file is only opened for writing in append mode (mode "'a'"),
   this method is essentially a no-op, but it remains useful for files
   opened in append mode with reading enabled (mode "'a+'").  If the
   file is opened in text mode (without "'b'"), only offsets returned
   by "tell()" are legal.  Use of other offsets causes undefined
   behavior.

   Note that not all file objects are seekable.

   버전 2.6으로 변경: Passing float values as offset has been
   deprecated.

file.tell()

   Return the file's current position, like "stdio"'s "ftell()".

   주석: On Windows, "tell()" can return illegal values (after an
     "fgets()") when reading files with Unix-style line-endings. Use
     binary mode ("'rb'") to circumvent this problem.

file.truncate([size])

   Truncate the file's size.  If the optional *size* argument is
   present, the file is truncated to (at most) that size.  The size
   defaults to the current position. The current file position is not
   changed.  Note that if a specified size exceeds the file's current
   size, the result is platform-dependent:  possibilities include that
   the file may remain unchanged, increase to the specified size as if
   zero-filled, or increase to the specified size with undefined new
   content. Availability:  Windows, many Unix variants.

file.write(str)

   Write a string to the file.  There is no return value.  Due to
   buffering, the string may not actually show up in the file until
   the "flush()" or "close()" method is called.

file.writelines(sequence)

   Write a sequence of strings to the file.  The sequence can be any
   iterable object producing strings, typically a list of strings.
   There is no return value. (The name is intended to match
   "readlines()"; "writelines()" does not add line separators.)

Files support the iterator protocol.  Each iteration returns the same
result as "readline()", and iteration ends when the "readline()"
method returns an empty string.

File objects also offer a number of other interesting attributes.
These are not required for file-like objects, but should be
implemented if they make sense for the particular object.

file.closed

   bool indicating the current state of the file object.  This is a
   read-only attribute; the "close()" method changes the value. It may
   not be available on all file-like objects.

file.encoding

   The encoding that this file uses. When Unicode strings are written
   to a file, they will be converted to byte strings using this
   encoding. In addition, when the file is connected to a terminal,
   the attribute gives the encoding that the terminal is likely to use
   (that  information might be incorrect if the user has misconfigured
   the  terminal). The attribute is read-only and may not be present
   on all file-like objects. It may also be "None", in which case the
   file uses the system default encoding for converting Unicode
   strings.

   버전 2.3에 추가.

file.errors

   The Unicode error handler used along with the encoding.

   버전 2.6에 추가.

file.mode

   The I/O mode for the file.  If the file was created using the
   "open()" built-in function, this will be the value of the *mode*
   parameter.  This is a read-only attribute and may not be present on
   all file-like objects.

file.name

   If the file object was created using "open()", the name of the
   file. Otherwise, some string that indicates the source of the file
   object, of the form "<...>".  This is a read-only attribute and may
   not be present on all file-like objects.

file.newlines

   If Python was built with *universal newlines* enabled (the default)
   this read-only attribute exists, and for files opened in universal
   newline read mode it keeps track of the types of newlines
   encountered while reading the file. The values it can take are
   "'\r'", "'\n'", "'\r\n'", "None" (unknown, no newlines read yet) or
   a tuple containing all the newline types seen, to indicate that
   multiple newline conventions were encountered. For files not opened
   in universal newlines read mode the value of this attribute will be
   "None".

file.softspace

   Boolean that indicates whether a space character needs to be
   printed before another value when using the "print" statement.
   Classes that are trying to simulate a file object should also have
   a writable "softspace" attribute, which should be initialized to
   zero.  This will be automatic for most classes implemented in
   Python (care may be needed for objects that override attribute
   access); types implemented in C will have to provide a writable
   "softspace" attribute.

   주석: This attribute is not used to control the "print"
     statement, but to allow the implementation of "print" to keep
     track of its internal state.


5.10. memoryview type
=====================

버전 2.7에 추가.

"memoryview" objects allow Python code to access the internal data of
an object that supports the buffer protocol without copying.  Memory
is generally interpreted as simple bytes.

class memoryview(obj)

   Create a "memoryview" that references *obj*.  *obj* must support
   the buffer protocol.  Built-in objects that support the buffer
   protocol include "str" and "bytearray" (but not "unicode").

   A "memoryview" has the notion of an *element*, which is the atomic
   memory unit handled by the originating object *obj*.  For many
   simple types such as "str" and "bytearray", an element is a single
   byte, but other third-party types may expose larger elements.

   "len(view)" returns the total number of elements in the memoryview,
   *view*.  The "itemsize" attribute will give you the number of bytes
   in a single element.

   A "memoryview" supports slicing to expose its data.  Taking a
   single index will return a single element as a "str" object.  Full
   slicing will result in a subview:

      >>> v = memoryview('abcefg')
      >>> v[1]
      'b'
      >>> v[-1]
      'g'
      >>> v[1:4]
      <memory at 0x77ab28>
      >>> v[1:4].tobytes()
      'bce'

   If the object the memoryview is over supports changing its data,
   the memoryview supports slice assignment:

      >>> data = bytearray('abcefg')
      >>> v = memoryview(data)
      >>> v.readonly
      False
      >>> v[0] = 'z'
      >>> data
      bytearray(b'zbcefg')
      >>> v[1:4] = '123'
      >>> data
      bytearray(b'z123fg')
      >>> v[2] = 'spam'
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      ValueError: cannot modify size of memoryview object

   Notice how the size of the memoryview object cannot be changed.

   "memoryview" has two methods:

   tobytes()

      Return the data in the buffer as a bytestring (an object of
      class "str").

         >>> m = memoryview("abc")
         >>> m.tobytes()
         'abc'

   tolist()

      Return the data in the buffer as a list of integers.

         >>> memoryview("abc").tolist()
         [97, 98, 99]

   몇 가지 읽기 전용 어트리뷰트도 사용할 수 있습니다:

   format

      A string containing the format (in "struct" module style) for
      each element in the view.  This defaults to "'B'", a simple
      bytestring.

   itemsize

      The size in bytes of each element of the memoryview.

   shape

      N-차원 배열로서의 메모리의 모양을 가리키는, 길이 "ndim" 인 정수
      의 튜플입니다.

   ndim

      메모리가 나타내는 다차원 배열의 차원 수를 나타내는 정수.

   strides

      배열의 각 차원에 대해 각 요소를 참조하는데 필요한 바이트 수를 제
      공하는, 길이 "ndim" 인 정수의 튜플입니다.

   readonly

      메모리가 읽기 전용인지 여부를 나타내는 논리값.


5.11. 컨텍스트 관리자 형
========================

버전 2.5에 추가.

Python's "with" statement supports the concept of a runtime context
defined by a context manager.  This is implemented using two separate
methods that allow user-defined classes to define a runtime context
that is entered before the statement body is executed and exited when
the statement ends.

The *context management protocol* consists of a pair of methods that
need to be provided for a context manager object to define a runtime
context:

contextmanager.__enter__()

   실행시간 컨텍스트에 진입하고 이 객체 자신이나 실행 시간 컨텍스트와
   관련된 다른 객체를 돌려줍니다. 이 메서드가 돌려주는 값은, 이 컨텍스
   트 관리자를 사용하는 "with" 문의 "as" 절의 식별자에 연결됩니다.

   An example of a context manager that returns itself is a file
   object. File objects return themselves from __enter__() to allow
   "open()" to be used as the context expression in a "with"
   statement.

   관련 객체를 돌려주는 컨텍스트 관리자의 예는
   "decimal.localcontext()" 가 돌려주는 것입니다. 이 관리자들은 활성
   십진 소수 컨텍스트를 원래 십진 소수 컨텍스트의 복사본으로 설정한 다
   음 복사본을 돌려줍니다. 이것은 "with" 문 바깥의 코드에 영향을 주지
   않으면서 "with" 문 바디에 있는 현재 십진 소수 컨텍스트를 변경할 수
   있게 합니다.

contextmanager.__exit__(exc_type, exc_val, exc_tb)

   실행 시간 컨텍스트를 탈출하고 발생한 예외를 막아야 하는지를 가리키
   는 논리 플래그를 돌려줍니다. "with" 문의 바디를 실행하는 동안 예외
   가 발생하면, 인자에 예외 형, 값 및 추적 정보가 포함됩니다. 그렇지
   않으면, 세 가지 인자 모두 "None" 입니다.

   이 메서드에서 참 값을 돌려주면 "with" 문이 예외를 막고 "with" 문 바
   로 뒤에 오는 문장에서 계속 실행됩니다. 그 이외의 경우, 이 메서드의
   실행이 완료된 후에 예외는 계속 퍼집니다. 이 메서드의 실행 중에 발생
   하는 예외는 "with" 문의 바디에서 발생한 모든 예외를 대체합니다.

   The exception passed in should never be reraised explicitly -
   instead, this method should return a false value to indicate that
   the method completed successfully and does not want to suppress the
   raised exception. This allows context management code (such as
   "contextlib.nested") to easily detect whether or not an
   "__exit__()" method has actually failed.

파이썬은 쉬운 스레드 동기화, 파일이나 다른 객체의 신속한 닫기, 그리고
활성 십진 소수 산술 컨텍스트의 보다 간단한 조작을 지원하기 위해 몇 가
지 컨텍스트 관리자를 정의합니다. 컨텍스트 관리 프로토콜의 구현을 넘어
구체적인 형은 특별히 취급되지 않습니다. 몇 가지 예제는 "contextlib" 모
듈을 보십시오.

Python's *generator*s and the "contextlib.contextmanager" *decorator*
provide a convenient way to implement these protocols.  If a generator
function is decorated with the "contextlib.contextmanager" decorator,
it will return a context manager implementing the necessary
"__enter__()" and "__exit__()" methods, rather than the iterator
produced by an undecorated generator function.

파이썬/C API의 파이썬 객체에 대한 형 구조체에는 이러한 메서드들을 위해
준비된 슬롯이 없다는 점에 유의하십시오. 이러한 메서드를 정의하고자 하
는 확장형은 일반적인 파이썬 액세스가 가능한 메서드로 제공해야 합니다.
실행 시간 컨텍스트를 설정하는 오버헤드와 비교할 때 한 번의 클래스 딕셔
너리 조회의 오버헤드는 무시할 수 있습니다.


5.12. 기타 내장형
=================

인터프리터는 여러 가지 다른 객체를 지원합니다. 이것들 대부분은 한두 가
지 연산만 지원합니다.


5.12.1. 모듈
------------

모듈에 대한 유일한 특별한 연산은 어트리뷰트 액세스입니다: "m.name". 여
기서 *m* 은 모듈이고 *name* 은 *m* 의 심볼 테이블에 정의된 이름에 액세
스합니다. 모듈 어트리뷰트는 대입할 수 있습니다. ("import" 문은 엄밀히
말하면 모듈 객체에 대한 연산이 아닙니다; "import foo" 는 *foo* 라는 이
름의 모듈 객체가 존재할 것을 요구하지 않고, 어딘가에 있는 *foo* 라는
이름의 (외부) *정의* 를 요구합니다.

모든 모듈의 특수 어트리뷰트는 "__dict__" 입니다. 이것은 모듈의 심볼 테
이블을 저장하는 딕셔너리입니다. 이 딕셔너리를 수정하면 모듈의 심볼 테
이블이 실제로 변경되지만, "__dict__" 어트리뷰트에 대한 직접 대입은 불
가능합니다 ("m.__dict__['a'] = 1" 라고 쓸 수 있고, "m.a" 가 "1" 이 되
지만, "m.__dict__ = {}" 라고 쓸 수는 없습니다). "__dict__" 의 직접적인
수정은 추천하지 않습니다.

인터프리터에 내장된 모듈은 다음과 같이 쓰입니다: "<module 'sys'
(built-in)>". 파일에서 로드되면, "<module 'os' from
'/usr/local/lib/pythonX.Y/os.pyc'>" 처럼 쓰입니다.


5.12.2. 클래스와 클래스 인스턴스
--------------------------------

여기에 대해서는 객체, 값, 형와 클래스 정의를 참조하세요.


5.12.3. 함수
------------

함수 객체는 함수 정의로 만들어집니다. 함수 객체에 대한 유일한 연산은
호출하는 것입니다: "func(argument-list)".

함수 객체에는 내장 함수와 사용자 정의 함수라는 두 가지 종류가 있습니다
. 두 함수 모두 같은 연산(함수 호출)을 지원하지만, 구현이 다르므로 서로
다른 객체 형입니다.

자세한 정보는 함수 정의을 보십시오.


5.12.4. 메서드
--------------

메서드는 어트리뷰트 표기법을 사용하여 호출되는 함수입니다. 두 가지 종
류가 있습니다: 내장 메서드(리스트의 "append()" 같은 것들)와 클래스 인
스턴스 메서드. 내장 메서드는 이를 지원하는 형에서 설명됩니다.

The implementation adds two special read-only attributes to class
instance methods: "m.im_self" is the object on which the method
operates, and "m.im_func" is the function implementing the method.
Calling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to
calling "m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)".

Class instance methods are either *bound* or *unbound*, referring to
whether the method was accessed through an instance or a class,
respectively.  When a method is unbound, its "im_self" attribute will
be "None" and if called, an explicit "self" object must be passed as
the first argument.  In this case, "self" must be an instance of the
unbound method's class (or a subclass of that class), otherwise a
"TypeError" is raised.

Like function objects, methods objects support getting arbitrary
attributes. However, since method attributes are actually stored on
the underlying function object ("meth.im_func"), setting method
attributes on either bound or unbound methods is disallowed.
Attempting to set an attribute on a method results in an
"AttributeError" being raised.  In order to set a method attribute,
you need to explicitly set it on the underlying function object:

   >>> class C:
   ...     def method(self):
   ...         pass
   ...
   >>> c = C()
   >>> c.method.whoami = 'my name is method'  # can't set on the method
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   AttributeError: 'instancemethod' object has no attribute 'whoami'
   >>> c.method.im_func.whoami = 'my name is method'
   >>> c.method.whoami
   'my name is method'

자세한 정보는 표준형 계층를 보십시오.


5.12.5. 코드 객체
-----------------

Code objects are used by the implementation to represent "pseudo-
compiled" executable Python code such as a function body. They differ
from function objects because they don't contain a reference to their
global execution environment.  Code objects are returned by the built-
in "compile()" function and can be extracted from function objects
through their "func_code" attribute. See also the "code" module.

A code object can be executed or evaluated by passing it (instead of a
source string) to the "exec" statement or the built-in "eval()"
function.

자세한 정보는 표준형 계층를 보십시오.


5.12.6. 형 객체
---------------

형 객체는 다양한 객체 형을 나타냅니다. 객체의 형은 내장 함수 "type()"
으로 액세스할 수 있습니다. 형에는 특별한 연산이 없습니다. 표준 모듈
"types" 는 모든 표준 내장형의 이름을 정의합니다.

Types are written like this: "<type 'int'>".


5.12.7. 널 객체
---------------

This object is returned by functions that don't explicitly return a
value.  It supports no special operations.  There is exactly one null
object, named "None" (a built-in name).

"None" 이라고 쓰입니다.


5.12.8. Ellipsis 객체
---------------------

This object is used by extended slice notation (see 슬라이싱
(Slicings)).  It supports no special operations.  There is exactly one
ellipsis object, named "Ellipsis" (a built-in name).

It is written as "Ellipsis".  When in a subscript, it can also be
written as "...", for example "seq[...]".


5.12.9. NotImplemented 객체
---------------------------

This object is returned from comparisons and binary operations when
they are asked to operate on types they don't support. See 비교 for
more information.

"NotImplemented" 로 쓰입니다.


5.12.10. 논리값
---------------

논리값은 두 개의 상수 객체인 "False" 와 "True" 입니다. 이것들은 논리값
을 나타내기 위해 사용됩니다 (하지만 다른 값도 거짓 또는 참으로 간주 될
수 있습니다). 숫자 컨텍스트(예를 들어, 산술 연산자의 인자로 사용될 때)
에서는 각각 정수 0과 1처럼 작동합니다. 내장 함수 "bool()" 은 값이 논리
값으로 해석될 수 있는 경우 모든 값을 논리값으로 변환하는 데 사용할 수
있습니다 (위의 논리값 검사 절을 참조하세요).

각각 "False" 과 "True" 로 쓰입니다.


5.12.11. 내부 객체
------------------

여기에 관한 정보는 표준형 계층를 참조하십시오. 스택 프레임 객체, 트레
이스백 객체 및 슬라이스 객체에 관해 설명합니다.


5.13. 특수 어트리뷰트
=====================

관련성이 있을 때, 구현은 몇 가지 객체 유형에 몇 가지 특수 읽기 전용 어
트리뷰트를 추가합니다. 이 중 일부는 "dir()" 내장 함수에 의해 보고되지
않습니다.

object.__dict__

   객체의 (쓰기 가능한) 어트리뷰트를 저장하는 데 사용되는 딕셔너리나
   또는 기타 매핑 객체.

object.__methods__

   버전 2.2 폐지: Use the built-in function "dir()" to get a list of
   an object's attributes. This attribute is no longer available.

object.__members__

   버전 2.2 폐지: Use the built-in function "dir()" to get a list of
   an object's attributes. This attribute is no longer available.

instance.__class__

   클래스 인스턴스가 속한 클래스.

class.__bases__

   클래스 객체의 베이스 클래스들의 튜플.

definition.__name__

   The name of the class, type, function, method, descriptor, or
   generator instance.

The following attributes are only supported by *new-style class*es.

class.__mro__

   이 어트리뷰트는 메서드 결정 중에 베이스 클래스를 찾을 때 고려되는
   클래스들의 튜플입니다.

class.mro()

   이 메서드는 인스턴스의 메서드 결정 순서를 사용자 정의하기 위해 메타
   클래스가 재정의할 수 있습니다. 클래스 인스턴스를 만들 때 호출되며
   그 결과는 "__mro__" 에 저장됩니다.

class.__subclasses__()

   Each new-style class keeps a list of weak references to its
   immediate subclasses.  This method returns a list of all those
   references still alive. Example:

      >>> int.__subclasses__()
      [<type 'bool'>]

-[ 각주 ]-

[1] 이 특수 메서드에 대한 추가 정보는 파이썬 레퍼런스 설명서(기본
    적인 커스터마이제이션)에서 찾을 수 있습니다.

[2] 결과적으로, 리스트 "[1, 2]" 는 "[1.0, 2.0]" 과 같다고 취급되고
    , 튜 플도 마찬가지입니다.

[3] 파서가 피연산자 유형을 알 수 없으므로 그럴 수밖에 없습니다.

[4] 케이스 문자는 일반 범주 속성이 "Lu" (Letter, 대문자), "Ll"
    (Letter, 소문자), "Lt" (Letter, 제목 문자) 중 한 가지인 경우입니다
    .

[5] 그래서, 튜플만을 포매팅하려면 포맷할 튜플 하나만을 포함하는 1-
    튜플 을 제공해야 합니다.

[6] The advantage of leaving the newline on is that returning an
    empty string is then an unambiguous EOF indication.  It is also
    possible (in cases where it might matter, for example, if you want
    to make an exact copy of a file while scanning its lines) to tell
    whether the last line of a file ended in a newline or not (yes
    this happens!).
