숫자형

# 정수형
a = 123

# 실수형
a = 1.2

# 8진수와 16진수
a = 0o177
a = 0x8ff

# 사칙연산
a = 3
b = 4
a + b
7
a * b
12
a / b
0.75

# 제곱
a = 3
b = 4
a ** b
81

# 나머지
7 % 3
1
3 % 7
3

# 몫을 반환
7 / 4
1.75



문자열

"Hello World"
'Python is fun'
"""Life is too short, You need python"""
'''Life is too short, You need python'''
multiline='''
... Life is too short
... You need python
... '''

# Concatenation
head = "Python"
tail = " is fun!"
head + tail
'Python is fun!'

# multiply
a = "python"
a * 2
'pythonpython'

# length
a = "Life is too short"
len(a)

# indexing
a = "Life is too short, You need Python"
a[0]
'L'

# slicing
a[0:5]
'Life '
a[19:]
'You need Python'
a[:17]
'Life is too short'

# formatting
"I eat %d apples." % 3
'I eat 3 apples.'

"I eat %s apples." % "five"
'I eat five apples.'

"I eat %d apples." % number
'I eat 3 apples.'

number = 10
day = "three"
"I ate %d apples. so I was sick for %s days." % (number, day)
'I ate 10 apples. so I was sick for three days.'

"Error is %d%%." % 98
'Error is 98%.'

"%0.4f" % 3.42134234
'3.4213'

"I eat {0} apples".format(3)
'I eat 3 apples'

- 왼쪽 정렬
"{0:<10}".format("hi")
'hi        '

- 오른쪽 정렬
"{0:>10}".format("hi")
'        hi'

- 가운데 정렬
"{0:^10}".format("hi")
'    hi    '

- 공백 채우기
"{0:=^10}".format("hi")
'====hi===='
"{0:!<10}".format("hi")
'hi!!!!!!!!'

- 소수점 표현하기
y = 3.42134234
"{0:0.4f}".format(y)
'3.4213'

- { 또는 } 문자 표현하기
"".format()
'{ and }'

# count
a = "hobby"
a.count('b')
2

# find
a = "Python is the best choice"
a.find('b')
14
a.find('k')
-1

a = "Life is too short"
a.index('t')
8

# join
",".join('abcd')
'a,b,c,d'

# upper
a = "hi"
a.upper()
'HI'

# lower
a = "HI"
a.lower()
'hi'

# 왼쪽 공백 지우기
a = " hi "
a.lstrip()
'hi '

# 오른쪽 공백 지우기
a= " hi "
a.rstrip()
' hi'

# 양쪽 공백 지우기
a = " hi "
a.strip()
'hi'

# 문자열 바꾸기
a = "Life is too short"
a.replace("Life", "Your leg")
'Your leg is too short'

# 문자열 나누기
a = "Life is too short"
a.split()   - 아무 값도 안 넣으면 공백을 기준으로 나눔(스페이스, 탭, 엔터 등)
['Life', 'is', 'too', 'short']


list

odd = [1, 3, 5, 7, 9]
a = []
b = [1, 2, 3]
c = ['Life', 'is', 'too', 'short']
d = [1, 2, 'Life', 'is']
e = [1, 2, ['Life', 'is']]

# indexing
a = [1, 2, 3]
a
[1, 2, 3]

a[0]
1

a[0] + a[2]
4

a[-1] //마지막 요소
3

a = [1, 2, 3, ['a', 'b', 'c']]

a[0]
1

a[-1]
['a', 'b', 'c']

a[3]
['a', 'b', 'c']

a[-1][0]
'a'

a = [1, 2, ['a', 'b', ['Life', 'is']]]
a[2][2][0]
'Life'

# slicing
a = [1, 2, 3, 4, 5]
a[0:2]
[1, 2]

a = "12345"
a[0:2]
'12'

a = [1, 2, 3, 4, 5]
b = a[:2]
c = a[2:]
b
[1, 2]
c
[3, 4, 5]

# add
a = [1, 2, 3]
b = [4, 5, 6]
a + b
[1, 2, 3, 4, 5, 6]

# multiply
a = [1, 2, 3]
a * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

# length
a = [1, 2, 3]
len(a)
3

# fix
a = [1, 2, 3]
a[2] = 4
a
[1, 2, 4]

# del
a = [1, 2, 3]
del a[1]
a
[1, 3]

# append
a = [1, 2, 3]
a.append(4)
a
[1, 2, 3, 4]

a.append([5,6])
a
[1, 2, 3, 4, [5, 6]]

# sort
a = [1, 4, 3, 2]
a.sort()
a
[1, 2, 3, 4]

a = ['a', 'c', 'b']
a.sort()
a
['a', 'b', 'c']

# reverse
a = ['a', 'c', 'b']
a.reverse()
a
['b', 'c', 'a']

# index
a = [1,2,3]
a.index(3)
2
a.index(1)
0

# insert
a = [1, 2, 3]
a.insert(0, 4)
a
[4, 1, 2, 3]

# remove
a = [1, 2, 3, 1, 2, 3]
a.remove(3)
a
[1, 2, 1, 2, 3]

# pop
a = [1,2,3]
a.pop()
3
a
[1, 2]

# count
a = [1,2,3,1]
a.count(1)
2

# extend
a = [1,2,3]
a.extend([4,5])
a
[1, 2, 3, 4, 5]
b = [6, 7]
a.extend(b)
a
[1, 2, 3, 4, 5, 6, 7]


tuple

  • 리스트와 거의 비슷 튜플은 ()으로 둘러싼다.
  • 튜플은 값을 바꿀 수 없다.
t1 = ()
t2 = (1,)
t3 = (1,2,3)
t4 = 1, 2, 3
t5 = ('a','b',('ab','cd'))

# slicing
t1 = (1, 2, 'a', 'b')
t1[1:]
(2, 'a', 'b')

# add
t1 = (1, 2, 'a', 'b')
t2 = (3, 4)
t1 + t2
(1, 2, 'a', 'b', 3, 4)

# multiply
t2 = (3, 4)
t2*3
(3, 4, 3, 4, 3, 4)

# length
t1 = (1, 2, 'a', 'b')
len(t1)


dictionary

{Key1:Value1, Key2:Value2, Key3:Value3, …}

dic = {'name':'pey', 'phone':'0119993323', 'birth': '1118'}

>>> a = {1: 'a'}
>>> a[2] = 'b'
>>> a
{1: 'a', 2: 'b'}

#add1
>>> a['name'] = 'pey'
>>> a
{1: 'a', 2: 'b', 'name': 'pey'}

#add2
>>> a[3] = [1,2,3]
>>> a
{1: 'a', 2: 'b', 'name': 'pey', 3: [1, 2, 3]}

#delete
>>> del a[1]
>>> a
{2: 'b', 'name': 'pey', 3: [1, 2, 3]}

#key list
>>> a = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'}
>>> a.keys()
dict_keys(['name', 'phone', 'birth'])

#value list
>>> a.values()
dict_values(['pey', '0119993323', '1118'])

#key, value items
>>> a.items()
dict_items([('name', 'pey'), ('phone', '0119993323'), ('birth', '1118')])

#clear
>>> a.clear()
>>> a
{}

#get value by key
>>> a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'}
>>> a.get('name')
'pey'
>>> a.get('phone')
'0119993323'

#check key in dictionary
>>> a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'}
>>> 'name' in a
True
>>> 'email' in a
False



집합

집합에 관련된 것을 쉽게 처리하기 위해 만든 자료형

  • 특징
  • 중복을 허용하지 않는다.
  • 순서가 없다(Unordered)
>>> s1 = set([1,2,3])
>>> s1
{1, 2, 3}

>>> s2 = set("Hello")
>>> s2
{'e', 'H', 'l', 'o'}

#set to list
>>> s1 = set([1,2,3])
>>> l1 = list(s1)
>>> l1
[1, 2, 3]
>>> l1[0]
1

#set to tuple
>>> t1 = tuple(s1)
>>> t1
(1, 2, 3)
>>> t1[0]
1

#교집합
>>> s1 = set([1, 2, 3, 4, 5, 6])
>>> s2 = set([4, 5, 6, 7, 8, 9])

>>> s1 & s2
{4, 5, 6}

>>> s1.intersection(s2)
{4, 5, 6}

#합집합
>>> s1 | s2
{1, 2, 3, 4, 5, 6, 7, 8, 9}

>>> s1.union(s2)
{1, 2, 3, 4, 5, 6, 7, 8, 9}

#차집합
>>> s1 - s2
{1, 2, 3}
>>> s2 - s1
{8, 9, 7}

>>> s1.difference(s2)
{1, 2, 3}
>>> s2.difference(s1)
{8, 9, 7}

#add
>>> s1 = set([1, 2, 3])
>>> s1.add(4)
>>> s1
{1, 2, 3, 4}

#update
>>> s1 = set([1, 2, 3])
>>> s1.update([4, 5, 6])
>>> s1
{1, 2, 3, 4, 5, 6}

#remove
>>> s1 = set([1, 2, 3])
>>> s1.remove(2)
>>> s1
{1, 3}


boolean

참/거짓

>>> a = True
>>> b = False

>>> 1 == 1
True

문자열, 리스트, 튜플, 딕셔너리 등의 값이 비어 있으면(“ “, [ ], ( ), { }) 거짓


변수


#복사
[:] 리스트 전체를 가리킨다.

>>> a = [1, 2, 3]
>>> b = a[:]
>>> a[1] = 4
>>> a
[1, 4, 3]
>>> b
[1, 2, 3]

copy module이용

>>> from copy import copy
>>> b = copy(a)

#변수를 만드는 여러가지 방법
>>> a, b = ('python', 'life')

>>> (a, b) = 'python', 'life'

>>> [a,b] = ['python', 'life']

>>> a = b = 'python'
>>> a = 3
>>> b = 5
>>> a, b = b, a
>>> a
5
>>> b
3


출처

https://wikidocs.net/15 https://wikidocs.net/16 https://wikidocs.net/17 https://wikidocs.net/18