파이썬 기호 의미 - paisseon giho uimi

안녕하세요 BlockDMask 입니다.
파이썬 문자열 포매팅 방법들 % 서식기호, format함수, f-string중에서 % 서식 기호에 대해서 알아보려고 합니다.
format 함수에 대해서 알고 싶다면 [바로가기]

<목차>
1. % 포매팅이란?
2. % 포매팅 예제

1. 파이썬 문자열 포매팅 % 에 대해서


문자열 포맷팅(string formatting)이란?

문자열을 만들때 원하는 위치에 특정한 값(변수)를 삽입해서 문자열을 그때그때 이쁘게 출력하는 것을 의미합니다.

예를 들어 학생 출석을 부른다고 했을떄

print('김땡땡 왔나요?')
print('박땡땡 왔나요?')
print('이땡땡 왔나요?')
이런식으로 부를 수 있겠죠?
자세히 살펴보니 '~~ 왔나요' 부분은 공통적이고 앞에 학생 이름만 바뀌지 않나요?

이럴때 우리는

김땡땡, 박땡땡, 이땡땡 이름을 리스트 자료형에 넣고
print('%s 왔나요?') % names[i] 이런식으로 표현해서 이름을 순회 하면서 출력하도록 하면 됩니다.
이 예제는 아래에서 코드로 보기로 하고
아무튼 이렇게 문자열 중간 특정 부분에 우리가 원하는 값을 넣기 위해 사용하는 것을 포맷팅 이라고 합니다.

% 서식문자

% 서식문자의 모양은 % 기호 뒤에 자료형을 가리키는 문자가 옵니다.
이런식입니다.
만약 정수를 출력한다고 하면
% + d => %d
문자열 중간에 %d가 있으면 파이썬은 이 부분에 정수 타입의 숫자가 올거구나 알았어.
라고 인식하게 됩니다.

말로만 설명하면 눈에 안들어 오니 코드로 한번 볼까요?

결과값은 "my age %d"위치에 num이 들어가게 되어서 "my age 50" 이런식으로 들어가게 됩니다.
여기서 문자열 뒤에 % 를 붙이고 변수를 넣은 것을 잘 알아두셔야 합니다.

정수 뿐만 아니라 실수, 

% 서식문자를 이용한 문자열 출력 자료형은 딱 3개만 알면 됩니다.
%s -> 문자열
%d -> 정수
%f -> 실수

굳이 더 알고 싶다면 아래 세개도 알아두면 좋습니다.

%o -> 8진수
%x -> 16진수
%% -> 문자 % 표현

2. 파이썬 문자열 포매팅 % 예제


2-1) 문자열, 정수, 실수를 % 로 포매팅 해보기

names = ['kim', 'park', 'lee']

    print('my name is %s' % name)

s2 = 'give me %d won' % money

cs

결과

파이썬 기호 의미 - paisseon giho uimi

이렇게 문자열에는 %s를 쓰고, 정수에는 %d, 실수에는 %f를 사용하면 됩니다.

2-2) 포매팅 해야할 변수 값이 두 개 이상일때는 어떻게 하지?

# 출력해야할 값이 두개 이상인 경우 () 를 이용합니다.

s1 = 'my name is %s. age : %d' % ('blockdmask', 100)

s2 = 'my name is %s, age : %d, weight : %f, money : %d, etc : %s' % (name, age, weight, money, etc)

cs

결과

파이썬 기호 의미 - paisseon giho uimi

이렇게 출력이 많을때는 ()를 이용해서 순서에 맞게 입력해주면 됩니다.
% 서식 문자를 이용한 문자열 포매팅은 언뜻 보면 타입을 정해주기 때문에 정확해 보이지만, 타입을 정해야 하기 때문에 불편한 점도 존재합니다.

그래서 이걸 개선하기 위해서 지난시간에 말한 str.format 형식이 나오게 된것이고, 그 이후에 또 다음 포스팅에 언급할 f-string 방법이 나오게 된 것 입니다. 

본인의 취향에 맞게, 편리한 방법을 사용하면 좋을것 같습니다.
이상으로 오늘 파이썬 포매팅 방법 그 두번째 시간인 % 서식 문자를 이용한 방법에 대해서 알아보았습니다. 감사합니다.

예를 들어 x = 2+3이라고 입력하고 Shift-Enter를 치면 x라는 저장장소가 만들어지고 이곳에 오른 쪽에서 나오는 졀과를 저장합니다. 만약에 이전의 다른 줄에 x를 이미 썼으면 맨처음 x를 써서 처음 만들어졌던 저장장소를 재활용해서 씁니다.

다음의 경우를 보겠습니다.

a=2
b=3
c=a+b
c=a*b

첫줄 a=2는 a라는 저장장소(변수)를 만들고 그곳에 2라는 숫자를 저장합니다.
둘째줄 b=3은 b라는 저장장소(변수)를 만들고 그곳에 3이라는 숫자를 저장합니다.
셋째줄 c=a+b은 c라는 저장장소(변수)를 만들고 그곳에 a+b의 결과를 저장합니다. 이미 a와 b 저장장소(변수)에 2와 3이 저장되어있으므로 2+3의 결과 5가 c에 저장됩니다.
넷째줄 c=a*b에서 c는 이미 셋째줄에서 만들어졌으므로 여기에서는 셋째줄에서 만들어진 저장장소(변수)를 재활용합니다. a*b 다시 말해 2*3의 결과 6이 재활용되는 c 저장장소(변수)에 저장됩니다.

그러면 양쪽이 같다라는 의미로 쓰는 기호는 =대신 =를 연속해서 두번 쓴 ==라는 기호를 씁니다.
이나마도 수학에서 양쪽이 서로 같다고 조금 다른 의미를 지닙니다.
==기호 양쪽이 같으냐라고 묻는 것에 대답을 결과를 내놓습니다.
예를 들면
2==2의 경우 2와 또다른 2가 같냐는 질문의 대답 True(참)을 결과로 내놓습니다.
2==3의 경우는 2와 3이 같냐는 질문의 대답 False(거짓짓)을 결과로 내놓습니다.
그나마 이대로 쓰고 나면 다음 줄에서 결과는 사라집니다.
이 때문에 True(참)인자 False(거짓)인지를 저장해놓았다가 쓰려면 다음과 같이 씁니다.

a=2
b=3
c=a==b

세번째 줄은 c=2==3과 같습니다. 2와 3은 달라 2==3은 거짓이 되므로 a==b는 False라는 결과를 내놓고 이를 c라는 기억장소(변수)에 저장합니다.
그런데 이렇게 다닥다닥 붙여놓으면 나중에 코드를 읽는데 헷갈길 수가 있어서 보통 왼쪽의 저장장소(변수)에 저장한다는 의미로 쓰는 = 기호 양쪽에 공란을 첨가해 다음과 같이 씁니다.

a = 2
b = 3
c = a==b

jupyter notebook을 실행해서 세줄을 입력한 다음 Shift-Enter를 쳐서 결과를 확인해보시기 바랍니다.

1980년대 후반에 ‘터보파스칼’이라는 프로그래밍 소프트웨어가 엄청 유행한 적이 있습니다. ‘파스칼'(PASCAL)이라는 프로그래밍 언어로 프로그래밍을 할 수 있게 하는 소프트웨어였습니다. 당시 배우기가 비교적 쉬운 언어여서 대학 정규 프로그래밍 강좌에서도 파스칼을 가르쳤습니다. 요즘 다들 파이썬(Python)을 배우듯이 말입니다.

파스칼이라는 언어에서는 변수에 결과를 저장하는 기호로 =가 아닌 := 기호를 썼습니다. 그리고 두 값이 같은지 비교하는 기호는 = 를 썼습니다. 베이직(BASIC) 언어도 값이 같은지 비교하는 기호로 =를 씁니다.

이 설명서에 나오는 많은 예는 (대화형 프롬프트에서 입력되는 것들조차도) 주석을 포함하고 있습니다. 파이썬에서 주석은 해시 문자,

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
1, 로 시작하고 줄의 끝까지 이어집니다. 주석은 줄의 처음에서 시작할 수도 있고, 공백이나 코드 뒤에 나올 수도 있습니다. 하지만 문자열 리터럴 안에는 들어갈 수 없습니다. 문자열 리터럴 안에 등장하는 해시 문자는 주석이 아니라 해시 문자일 뿐입니다. 주석은 코드의 의미를 정확히 전달하기 위한 것이고, 파이썬이 해석하지 않는 만큼, 예를 입력할 때는 생략해도 됩니다.

몇 가지 예를 듭니다:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."

3.1. 파이썬을 계산기로 사용하기¶

몇 가지 간단한 파이썬 명령을 사용해봅시다. 인터프리터를 실행하고 기본 프롬프트,

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
2, 를 기다리세요. (얼마 걸리지 않아야 합니다.)

3.1.1. 숫자¶

인터프리터는 간단한 계산기로 기능합니다: 표현식을 입력하면 값을 출력합니다. 표현식 문법은 간단합니다.

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
3,
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
4,
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
5,
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
6 연산자들은 대부분의 다른 언어들 (예를 들어, 파스칼이나 C)처럼 동작합니다; 괄호 (
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
7) 는 묶는 데 사용합니다. 예를 들어:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6

정수 (예를 들어

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
8,
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
9,
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
0)는
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
1 형입니다. 소수부가 있는 것들 (예를 들어
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
2,
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
3)은
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
4 형입니다. 이 자습서 뒤에서 숫자 형들에 관해 더 자세히 살펴볼 예정입니다.

나눗셈 (

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
6) 은 항상 float를 돌려줍니다. 정수 나눗셈 으로 (소수부 없이) 정수 결과를 얻으려면
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
6 연산자를 사용하면 됩니다; 나머지를 얻으려면
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
7 를 사용할 수 있습니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

파이썬에서는 거듭제곱을 계산할 때

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
8 연산자를 사용합니다 1:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

변수에 값을 대입할 때는 등호(

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
9)를 사용합니다. 이 경우 다음 대화형 프롬프트 전에 표시되는 출력은 없습니다:

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

변수가 《정의되어》 있지 않을 때 (값을 대입하지 않았을 때) 사용하려고 시도하는 것은 에러를 일으킵니다:

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

실수를 본격적으로 지원합니다; 서로 다른 형의 피연산자를 갖는 연산자는 정수 피연산자를 실수로 변환합니다:

>>> 4 * 3.75 - 1
14.0

대화형 모드에서는, 마지막에 인쇄된 표현식은 변수

>>> 4 * 3.75 - 1
14.0
0 에 대입됩니다. 이것은 파이썬을 탁상용 계산기로 사용할 때, 계산을 이어 가기가 좀 더 쉬워짐을 의미합니다. 예를 들어:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

이 변수는 사용자로서는 읽기만 가능한 것처럼 취급되어야 합니다. 값을 직접 대입하지 마세요 — 만약 그렇게 한다면 같은 이름의 지역 변수를 새로 만드는 것이 되는데, 내장 변수의 마술 같은 동작을 차단하는 결과를 낳습니다.

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
1 와
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
4 에 더해, 파이썬은
>>> 4 * 3.75 - 1
14.0
3 이나
>>> 4 * 3.75 - 1
14.0
4 등의 다른 형의 숫자들도 지원합니다. 파이썬은 복소수 에 대한 지원도 내장하고 있는데, 허수부를 가리키는데
>>> 4 * 3.75 - 1
14.0
5 나
>>> 4 * 3.75 - 1
14.0
6 접미사를 사용합니다 (예를 들어
>>> 4 * 3.75 - 1
14.0
7).

3.1.2. 문자열¶

숫자와는 별개로, 파이썬은 문자열도 다룰 수 있는데 여러 가지 방법으로 표현됩니다. 작은따옴표(

>>> 4 * 3.75 - 1
14.0
8) 나 큰따옴표(
>>> 4 * 3.75 - 1
14.0
9)로 둘러쌀 수 있는데 모두 같은 결과를 줍니다 2. 따옴표를 이스케이핑 할 때는
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
0 를 사용할 수 있습니다:

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

대화형 인터프리터에서, 출력 문자열은 따옴표로 둘러싸여 있고, 특수 문자들은 역 슬래시로 이스케이핑 됩니다. 때로 입력한 것과 달라 보여도 (따옴표의 종류가 바뀔 수 있다), 두 문자열은 동등합니다. 문자열이 작은따옴표를 포함하고 큰따옴표를 포함하지 않으면 큰따옴표가 사용되고, 그 외의 경우는 작은따옴표가 사용됩니다.

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
1 함수는 따옴표를 생략하고, 이스케이핑된 특수 문자를 출력해서 더 읽기 쉬운 출력을 만들어냅니다:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
0 뒤에 나오는 문자가 특수 문자로 취급되게 하고 싶지 않다면, 첫 따옴표 앞에
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
3 을 붙여서 날 문자열 (raw string) 을 만들 수 있습니다:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
0

문자열 리터럴은 여러 줄로 확장될 수 있습니다. 한 가지 방법은 삼중 따옴표를 사용하는 것입니다:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
4 또는
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
5. 줄 넘김 문자는 자동으로 문자열에 포함됩니다. 하지만 줄 끝에
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
0 를 붙여 이를 방지할 수도 있습니다. 다음 예:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
1

는 이런 결과를 출력합니다 (첫 번째 개행문자가 포함되지 않는 것에 주목하세요):

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
2

문자열은

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
3 연산자로 이어붙이고,
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
5 연산자로 반복시킬 수 있습니다:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
3

두 개 이상의 문자열 리터럴 (즉, 따옴표로 둘러싸인 것들) 가 연속해서 나타나면 자동으로 이어 붙여집니다.

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
4

이 기능은 긴 문자열을 쪼개고자 할 때 특별히 쓸모 있습니다:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
5

이것은 오직 두 개의 리터럴에만 적용될 뿐 변수나 표현식에는 해당하지 않습니다:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
6

변수들끼리 혹은 변수와 문자열 리터럴을 이어붙이려면

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
3 를 사용해야 합니다

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
7

문자열은 인덱스 (서브 스크립트) 될 수 있습니다. 첫 번째 문자가 인덱스 0에 대응됩니다. 문자를 위한 별도의 형은 없습니다; 단순히 길이가 1인 문자열입니다:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
8

인덱스는 음수가 될 수도 있는데, 끝에서부터 셉니다:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
9

-0은 0과 같으므로, 음의 인덱스는 -1에서 시작한다는 것에 주목하세요.

인덱싱에 더해 슬라이싱(slicing) 도 지원됩니다. 인덱싱이 개별 문자를 얻는데 사용되는 반면, 슬라이싱 은 부분 문자열(substring)을 얻는 데 사용됩니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
0

시작 위치의 문자는 항상 포함되는 반면, 종료 위치의 문자는 항상 포함되지 않는 것에 주의하세요. 이 때문에

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
0 는 항상
>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
1 와 같아집니다

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
1

슬라이스 인덱스는 편리한 기본값을 갖고 있습니다; 첫 번째 인덱스를 생략하면 기본값 0 이 사용되고, 두 번째 인덱스가 생략되면 기본값으로 슬라이싱 되는 문자열의 길이가 사용됩니다.

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
2

슬라이스가 동작하는 방법을 기억하는 한 가지 방법은 인덱스가 문자들 사이의 위치를 가리킨다고 생각하는 것입니다. 첫 번째 문자의 왼쪽 경계가 0입니다. n 개의 문자들로 구성된 문자열의 오른쪽 끝 경계는 인덱스 n 이 됩니다, 예를 들어:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
3

첫 번째 숫자 행은 인덱스 0…6 의 위치를 보여주고; 두 번째 행은 대응하는 음의 인덱스들을 보여줍니다. i 에서 j 범위의 슬라이스는 i 와 j 로 번호 붙여진 경계 사이의 문자들로 구성됩니다.

음이 아닌 인덱스들의 경우, 두 인덱스 모두 범위 내에 있다면 슬라이스의 길이는 인덱스 간의 차입니다. 예를 들어

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
2 의 길이는 2입니다.

너무 큰 값을 인덱스로 사용하는 것은 에러입니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
4

하지만, 범위를 벗어나는 슬라이스 인덱스는 슬라이싱할 때 부드럽게 처리됩니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
5

파이썬 문자열은 변경할 수 없다 — 불변 이라고 합니다. 그래서 문자열의 인덱스로 참조한 위치에 대입하려고 하면 에러를 일으킵니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
6

다른 문자열이 필요하면, 새로 만들어야 합니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
7

내장 함수

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
3 은 문자열의 길이를 돌려줍니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
8

더 보기

텍스트 시퀀스 형 — str

문자열은 시퀀스 형 의 일종이고, 시퀀스가 지원하는 공통 연산들이 지원됩니다.

문자열 메서드

문자열은 기본적인 변환과 검색을 위한 여러 가지 메서드들을 지원합니다.

포맷 문자열 리터럴

내장된 표현식을 갖는 문자열 리터럴

Format String Syntax

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
4 으로 문자열을 포맷하는 방법에 대한 정보.

printf 스타일 문자열 포매팅

이곳에서 문자열을

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
7 연산자 왼쪽에 사용하는 예전 방식의 포매팅에 관해 좀 더 상세하게 설명하고 있습니다.

3.1.3. 리스트¶

파이썬은 다른 값들을 덩어리로 묶는데 사용되는 여러 가지 컴파운드 (compound) 자료 형을 알고 있습니다. 가장 융통성이 있는 것은 리스트 인데, 꺾쇠괄호 사이에 쉼표로 구분된 값(항목)들의 목록으로 표현될 수 있습니다. 리스트는 서로 다른 형의 항목들을 포함할 수 있지만, 항목들이 모두 같은 형인 경우가 많습니다.

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
9

문자열(그리고, 다른 모든 내장 시퀀스 형들)처럼 리스트는 인덱싱하고 슬라이싱할 수 있습니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
0

모든 슬라이스 연산은 요청한 항목들을 포함하는 새 리스트를 돌려줍니다. 이는 다음과 같은 슬라이스가 리스트의 새로운 (얕은) 복사본을 돌려준다는 뜻입니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
1

리스트는 이어붙이기 같은 연산도 지원합니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
2

불변 인 문자열과는 달리, 리스트는 가변 입니다. 즉 내용을 변경할 수 있습니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
3

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
6 메서드 (method) (나중에 메서드에 대해 더 자세히 알아볼 것입니다) 를 사용하면 리스트의 끝에 새 항목을 추가할 수 있습니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
4

슬라이스에 대입하는 것도 가능한데, 리스트의 길이를 변경할 수 있고, 모든 항목을 삭제할 수조차 있습니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
5

내장 함수

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
3 은 리스트에도 적용됩니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
6

리스트를 중첩할 수도 있습니다. (다른 리스트를 포함하는 리스트를 만듭니다). 예를 들어:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
7

3.2. 프로그래밍으로의 첫걸음¶

물론, 2 에 2를 더하는 것보다는 더 복잡한 방법으로 파이썬을 사용할 수 있습니다. 예를 들어, 다음처럼 피보나치 (Fibonacci) 수열의 앞부분을 계산할 수 있습니다:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
8

이 예는 몇 가지 새로운 기능을 소개하고 있습니다.

  • 첫 줄은 다중 대입 을 포함하고 있습니다: 변수

    >>> 'spam eggs'  # single quotes
    'spam eggs'
    >>> 'doesn\'t'  # use \' to escape the single quote...
    "doesn't"
    >>> "doesn't"  # ...or use double quotes instead
    "doesn't"
    >>> '"Yes," they said.'
    '"Yes," they said.'
    >>> "\"Yes,\" they said."
    '"Yes," they said.'
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    
    8 와
    >>> 'spam eggs'  # single quotes
    'spam eggs'
    >>> 'doesn\'t'  # use \' to escape the single quote...
    "doesn't"
    >>> "doesn't"  # ...or use double quotes instead
    "doesn't"
    >>> '"Yes," they said.'
    '"Yes," they said.'
    >>> "\"Yes,\" they said."
    '"Yes," they said.'
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    
    9 에 동시에 값 0과1이 대입됩니다. 마지막 줄에서 다시 사용되는데, 대입이 어느 하나라도 이루어지기 전에 우변의 표현식들이 모두 계산됩니다. 우변의 표현식은 왼쪽부터 오른쪽으로 가면서 순서대로 계산됩니다.

  • >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    0 루프는 조건(여기서는:
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    1)이 참인 동안 실행됩니다. C와 마찬가지로 파이썬에서 0 이 아닌 모든 정수는 참이고, 0은 거짓입니다. 조건은 문자열이나 리스트 (사실 모든 종류의 시퀀스)가 될 수도 있는데 길이가 0 이 아닌 것은 모두 참이고, 빈 시퀀스는 거짓입니다. 이 예에서 사용한 검사는 간단한 비교입니다. 표준 비교 연산자는 C와 같은 방식으로 표현됩니다:
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    2 (작다),
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    3 (크다),
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    4 (같다),
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    5 (작거나 같다),
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    6 (크거나 같다),
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print('"Isn\'t," they said.')
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print(), \n is included in the output
    'First line.\nSecond line.'
    >>> print(s)  # with print(), \n produces a new line
    First line.
    Second line.
    
    7 (다르다).

  • 루프의 바디 (body) 는 들여쓰기 됩니다. 들여쓰기는 파이썬에서 문장을 덩어리로 묶는 방법입니다. 대화형 프롬프트에서 각각 들여 쓰는 줄에서 탭(tab)이나 공백(space)을 입력해야 합니다. 실제적으로는 텍스트 편집기를 사용해서 좀 더 복잡한 파이썬 코드를 준비하게 됩니다; 웬만한 텍스트 편집기들은 자동 들여쓰기 기능을 제공합니다. 복합문을 대화형으로 입력할 때는 끝을 알리기 위해 빈 줄을 입력해야 합니다. (해석기가 언제 마지막 줄을 입력할지 짐작할 수 없기 때문입니다.) 같은 블록에 포함되는 모든 줄은 같은 양만큼 들여쓰기 되어야 함에 주의하세요.

  • >>> tax = 12.5 / 100
    >>> price = 100.50
    >>> price * tax
    12.5625
    >>> price + _
    113.0625
    >>> round(_, 2)
    113.06
    
    1 함수는 주어진 인자들의 값을 인쇄합니다. 다중 인자, 실수의 값, 문자열을 다루는 방식에서 (계산기 예제에서 본 것과 같이) 출력하고자 하는 표현식을 그냥 입력하는 것과는 다릅니다. 문자열은 따옴표 없이 출력되고, 인자들 간에는 빈칸이 삽입됩니다. 그래서 이런 식으로 보기 좋게 포매팅할 수 있습니다:

    >>> 5 ** 2  # 5 squared
    25
    >>> 2 ** 7  # 2 to the power of 7
    128
    
    9

    키워드 인자 end 는 출력 끝에 포함되는 개행문자를 제거하거나 출력을 다른 문자열로 끝나게 하고 싶을 때 사용됩니다:

    >>> width = 20
    >>> height = 5 * 9
    >>> width * height
    900
    
    0

각주

1

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
8 가
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
4 보다 우선순위가 높으므로,
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
01 는
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
02 를 사용할 수 있습니다.

2

다른 언어들과는 달리, `` `` 과 같은 특수 문자들은 작은따옴표(

>>> 4 * 3.75 - 1
14.0
8)와 큰따옴표(
>>> 4 * 3.75 - 1
14.0
9)에서 같은 의미가 있습니다. 둘 간의 유일한 차이는 작은따옴표 안에서
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
05 를 이스케이핑할 필요가 없고 (하지만
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
06 는 이스케이핑 시켜야 합니다), 그 역도 성립한다는 것입니다.