파이썬 문법 사전 - 숫자, 문자열, 리스트

파이썬 문법 사전 - 숫자, 문자열, 리스트

숫자


+, -, *, / 같이 사칙연산 연산자를 사용할 수 있다.
괄호는 연산의 우선순위를 정할 때 사용한다.

1
2
3
4
5
6
7
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

나눗셈은 항상 float을 리턴한다.
정수 나눗셈으로 정수 결과를 얻으려면 // 을 사용하면 된다.
나머지 연산에서는 %을 사용한다.

1
2
3
4
5
6
7
8
9
>>> 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
2
3
4
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128

변수를 값에 대입할 때는 등호 =를 사용한다.


문자열


파이썬에서 문자열은 ‘작은따옴표’나 “큰따옴표”로 둘러쌀 수 있고 둘다 같은 결과를 가져온다.
따옴표를 이스케이핑 하는 방법은 \를 사용하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
>>> '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.'

print()를 사용할 때 \뒤의 문자가 특수문자로 취급되게 하고 싶지 않다면, 첫 따옴표 앞에 r을 붙여서 raw string을 만들 수 있다.

1
2
3
4
5
>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name

삼중따옴표 “””, ‘’’를 통해 줄넘김 문자를 자동으로 문자열에 포함 할 수도 있다. 줄 끝에 \를 붙여 이를 무시할 수도 있다.
또 연산자를 이어 붙이기도 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
>>> 'Py' 'thon'
'Python'

문자열은 인덱스 될 수 있다. 첫 번째 문자가 인덱스 0에 대응된다. 인덱스는 음수가 될 수도 있다.
1
2
3
4
5
6
7
8
9
10
11
12
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'

>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'

슬라이싱도 지원한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'

이렇게 보면 이해하기 쉽다.

1
2
3
4
5
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1

범위 밖의 값을 인덱스로 사용하면 오류가 나지만 슬라이싱을 할 때는 부드럽게 처리된다.

파이썬의 문자열은 변경할 수 없다. 그래서 특정 인덱스의 값을 바꾸려 할 때는 에러가 난다. 만약 꼭 바꿔야한다면 새 문자열을 만들어야 한다.


내장함수 len()은 문자열의 길이를 반환한다.
1
2
3
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

리스트


대괄호 사이에 쉼표로 구분된 항목들의 목록으로 표현된다.
리스트는 서로 다른 자료형의 항목을 포함할 수 있다.

1
2
3
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

문자열과 마찬가지로 슬라이싱 가능하다.

1
2
3
4
5
6
>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]

리스트는 이어붙이기 가능하다.

1
2
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

문자열과 다르게 리스트는 내용을 변경할 수 있다.

1
2
3
4
>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

append() 메서드를 사용하면 리스트의 끝에 새 항목을 추가할 수 있다.

1
2
3
4
>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

슬라이싱 후 대입이 가능하기 때문에 길이변경과 항목삭제도 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

len()를 통해 길이를 가져올 수 있다.

Reference
python.org

이 게시물은 파이썬 문법을 까먹었을 때 검색하려고 작성됨.