goodthings4me.tistory.com
■ Built-in Data Type - int, float, complex, str, bool
>>>help() # 파이썬 도움말 보기
help>modules
>>> type(1)
<class 'int'>
>>> type(1.2)
<class 'float'>
>>> type(2+3j)
<class 'complex'>
>>> type('a')
<class 'str'>
>>> type('hello')
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> int()
0
>>> float()
0.0
>>> complex()
0j
>>> str()
''
>>> bool()
False
>>> int(1.3)
1
>>> float(1)
1.0
>>> int('1')
1
>>> int('1.3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.3'
>>> float('3.14')
3.14
>>> float('inf')
inf
>>> float('Inf')
inf
>>> 1e3
1000.0
>>> 1e-3
0.001
>>> 1/1e-3
1000.0
>>> 1/1e-256
1e+256
>>> 1/1e-310
inf
>>> complex(1)
(1+0j)
>>> complex(2j)
2j
>>> complex(3, 2.2)
(3+2.2j)
>>> complex('1+3j')
(1+3j)
>>> str(3.14)
'3.14'
>>> str(10)
'10'
>>> str(2+3j)
'(2+3j)'
>>> str('abc')
'abc'
>>> cls
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cls' is not defined
>>> import os
>>> os.system('cls')
>>> _ = os.system('cls')
>>> divmod(5, 3)
(1, 2)
>>> pow(2, 10)
1024
>>> 2**10
1024
>>>
>>> True + True # 1 + 1
2
>>> True + False
1
>>> False + False
0
>>> True / False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> False /True
0.0
>>> 2 is 1 # 숫자에는 '==' 사용 권장
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False
>>> 2 == 1
False
>>> type(3.0) is type(3)
False
>>> type(3.0) is not type(3)
True
>>> 100 and 1 # True
1
>>> 1 and 100
100
>>> 100 and 0 # False
0
>>> 0 and 100
0
>>> 100 or 1
100
>>> 1 or 100
1
>>> 100 or 0
100
>>> 0 or 100
100
>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin(10)
'0b1010'
>>> 10 & 6
2
>>> bin(10 & 6)
'0b10'
>>> bin(10 | 6)
'0b1110'
>>> bin(10)
'0b1010'
>>> bin(6)
'0b110'
>>> bin(10 ^ 6)
'0b1100'
>>> 10 ^ 6
12
>>> bin(6)
'0b110'
>>> bin(6 << 2)
'0b11000'
>>> bin(6 >> 2)
'0b1'
>>> a = 2
>>> bin(a)
'0b10'
>>> a.bit_length() # bit 2개 1 0
2
>>> b = 10
>>> b.bit_length()
4
>>> bin(b)
'0b1010'
>>> c = 1+2j
>>> c
(1+2j)
>>> c.conjugate() # 부호 빠꿔줌
(1-2j)
>>> c.real
1.0
>>> c.imag
2.0
>>> name = 'dongsoo'
>>> name.capitalize()
'Dongsoo'
>>> name.split('o')
['d', 'ngs', '', '']
>>> name.split('g')
['don', 'soo']
>>> name_split = name.split('g')
>>> type(name_split)
<class 'list'>
>>> name_split[1]
'soo'
>>> s = 'abc\def'
>>> s
'abc\\def' # 파이썬이 자동으로 \ 추가
>>> print(s)
abc\def
>>> text = 'I'm a Tom'
SyntaxError: invalid syntax
>>> text = "I'm a Tom"
>>> text
"I'm a Tom"
>>> text = 'I\'m a Tom'
>>> text
"I'm a Tom"
>>> dir_path = 'C:\\python\\My_project'
>>> dir_path
'C:\\python\\My_project'
>>> dir_path = r'C:\python395\My_project'
>>> dir_path
'C:\\python395\\My_project'
>>> dir_path = 'C:/python/My_priject'
>>> dir_path
'C:/python/My_priject'
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'c', 'dir_path', 'name', 'name_split', 's', 'text']
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'c': (1+2j),
'name': 'dongsoo', 'name_split': ['don', 'soo'], 's': 'abc\\def',
'text': "I'm a Tom", 'dir_path': 'C:/python/My_priject'}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
'c': (1+2j), 'name': 'dongsoo', 'name_split': ['don', 'soo'], 's': 'abc\\def',
'text': "I'm a Tom", 'dir_path': 'C:/python/My_priject'}
>>> a = 1
>>> b = 3
>>> a == b
False
>>> a.__eq__(b)
False
>>> dir(a)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',
'__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__',
'__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__',
'__getnewargs__', '__gt__', '__hash__', '__index__', '__init__',
'__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__',
'__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__',
'__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__',
'__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__',
'__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__',
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
'__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',
'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes',
'imag', 'numerator', 'real', 'to_bytes']
■ Continers - list, tuple, set, frozenset, dictionary
# list
my_list1 = [10, 20, 30, 40, 50]
print(my_list1[0:4:1]) # [10, 20, 30, 40]
print(my_list1[1:5:1]) # [20, 30, 40, 50]
print(my_list1[0:5:2]) # [10, 30, 50]
print(my_list1[-1::-1]) # [50, 40, 30, 20, 10]
print(my_list1[-1:-5:-1]) # [50, 40, 30, 20]
print(my_list1[-1:-6:-1]) # [50, 40, 30, 20, 10]
my_list2 = [100, 200]
print(my_list1 + my_list2) # [10, 20, 30, 40, 50, 100, 200]
my_list3 = [[10, 20], [30, 40]]
my_list4 = [[50, 60, 70], [80, 90]]
print(my_list3 + my_list4) # [[10, 20], [30, 40], [50, 60, 70], [80, 90]]
print(my_list2 * 2) # [100, 200, 100, 200]
print(my_list3 * 3) # [[10, 20], [30, 40], [10, 20], [30, 40], [10, 20], [30, 40]]
# list 복사 - 메모리 공간 공유
old_list = [10, 20, 30, 40]
new_list = old_list
print(new_list) # [10, 20, 30, 40]
print(new_list == old_list) # True
print(id(old_list), id(new_list)) # 1739338764864 1739338764864
print(new_list is old_list) # True
old_list[0] = 100
new_list[3] = 400
print(old_list) # [100, 20, 30, 400]
print(new_list) # [100, 20, 30, 400]
# .copy() 함수
old_list = [100, 200]
new_list = old_list.copy()
print(new_list)
print(new_list == old_list) # True
print(id(old_list), id(new_list)) # 1739342684736 1739343138752
print(new_list is old_list) # False
old_list[0] = 1000
new_list[1] = 4000
print(old_list) # [1000, 200]
print(new_list) # [100, 4000]
print(new_list == old_list) # False
# append()
num_list1 = [10, 20, 30]
num_list1.append(40)
num_list1.append([50])
print(num_list1) # [10, 20, 30, 40, [50]]
# extend()
num_list2 = [10, 20, 30]
# num_list2.extend(40) # TypeError: 'int' object is not iterable
num_list2.extend([50])
print(num_list2) # [10, 20, 30, 50]
print(num_list2 + [60]) # [10, 20, 30, 50, 60]
# 제거 - remove() pop() clear()
num_list1.remove(30)
print(num_list1) # [10, 20, 40, [50]]
# num_list1.remove(0) # ValueError: list.remove(x): x not in list
print(num_list1) # [10, 20, 40, [50]]
print(num_list1.pop(0)) #
print(num_list1.clear()) # None / clear() - 모든 요소 지우기
print(num_list1) # []
# insert()
num_list1.insert(0, 'Newton')
num_list1.insert(5, 'Gauss') # 지정 index가 아닌 1번째에 insert
print(num_list1.index('Gauss')) # 1 - index('element') : element index 반환
num_list1.insert(2, 'Euelr')
print(num_list1) # ['Newton', 'Gauss', 'Euelr']
# sort() sorted()
lst = sorted(num_list1) # 원본에 영향 없음
print(lst) # ['Euelr', 'Gauss', 'Newton']
print(num_list1) # ['Newton', 'Gauss', 'Euelr']
num_list1.sort() # 원본 정렬
print(num_list1) # ['Euelr', 'Gauss', 'Newton']
num_list1.reverse()
print(num_list1) # ['Newton', 'Gauss', 'Euelr']
# set
my_set1 = {10, 20, 30, 20}
my_set2 = {10, 'tip', True}
# print(my_set1[0]) # TypeError: 'set' object is not subscriptable
print(my_set1) # {10, 20, 30} 중복(20) 제거
my_list = [10, 20, 30, 40, 50]
my_set3 = set(my_list)
print(my_set3) # {40, 10, 50, 20, 30} 순서(order) 없음
my_set4 = set()
print(my_set4) # set()
my_set4.add(30)
my_set4.update([50, 20]) # 리스트 또는 튜플로 업데이트
my_set4.update((80, 10))
print(my_set4) # {10, 80, 50, 20, 30}
my_set4.remove(80)
print(my_set4) # {10, 50, 20, 30}
my_set4.discard(10)
print(my_set4) # {50, 20, 30}
# my_set4.remove(10) # KeyError: 10
my_set4.discard(10) # 에러 발생 안함 (remove()와의 차이점)
A = {10, 20, 30, 40, 50}
B = {40, 50, 60, 70, 80}
print(A | B) # {70, 40, 10, 80, 50, 20, 60, 30} A.union(B)
print(A & B) # {40, 50} A.intersection(B)
print(A-B) # {10, 20, 30} A.difference(B)
print(A^B) # {80, 20, 70, 10, 60, 30} A.symmetric_difference(B)
a = {10, 20, 30, 40, 50}
b = {40}
print(b.issubset(a)) # True b의 모든 값이 a에 포함되었나
print(a.issubset(b)) # False
print(b.issuperset(a)) # False b의 모든 값이 a에 포함되었나
print(a.issuperset(b)) # True
fsetA = frozenset([10, 20, 30, 40, 50])
fsetB = frozenset([40, 50, 60, 70, 80])
print(fsetA) # frozenset({40, 10, 50, 20, 30})
print(fsetB) # frozenset({70, 40, 80, 50, 60})
print(fsetA & fsetB) # frozenset({40, 50})
print(fsetA | fsetB) # frozenset({70, 40, 10, 80, 50, 20, 60, 30})
# fsetA.add(60) # AttributeError: 'frozenset' object has no attribute 'add'
setB = {40, 50, 60, 70, 80}
print(fsetA & setB) # frozenset({40, 50})
# dictionary
phone_book = {'Dongsoo': '111-1111',
'Jason': '222-2222',
'David': '333-3333'}
print(phone_book.get('Jason')) # 222-2222
phone_book['Jason'] = '555-5555'
phone_book.update({'David': '666-6666'}) # update({})
print(phone_book) # {'Dongsoo': '111-1111', 'Jason': '555-5555', 'David': '666-6666'}
print(phone_book.pop('Dongsoo')) # 111-1111 pop() 삭제
print(phone_book) # {'Jason': '555-5555', 'David': '666-6666'}
phone_book.clear()
print(phone_book) # {}
# 컨테이너 관련 내장 함수
lst = [10, 20, 30, 40, 50]
tp = (10, 20, 30, 40, 50)
st = {10, 20, 30, 40, 50}
a = 1
# print(len(1)) # TypeError: object of type 'int' has no len()
print(len(lst), len(tp), len(st)) # 5 5 5
print(max(lst), max(tp), max(st)) # 50 50 50
print(min(lst), min(tp), min(st)) # 10 10 10
print(30 in lst, 30 in tp, 30 in st) # True True True
# 리스트 언패킹(list unpacking)
member = ['kebin', 24, 'Python']
name, age, language = member
print(name) # kebin
print(age) # 24
print(language) # Python
name, *pdata = member
print(*pdata) # 24 Python
numbers = [10, 20, 30, 40, 50]
first, *rest = numbers
print(first) # 10
print(*rest) # 20 30 40 50
*rest, last = numbers
print(*rest) # 10 20 30 40
print(last) # 50
first, second, *rest = numbers
print(*rest) # 30 40 50
first, *body, last = numbers
print(*body) # 20 30 40
# range
print(int) # <class 'int'>
print(range) # <class 'range'>
print(type(int)) # <class 'type'>
print(type(range)) #<class 'type'>
print(10 in range(0, 20, 2)) # True
print(11 in range(1, 20, 2)) # True
■ string (str)
s = 'Python' # 문자 하나 하나의 컨테이너
print(repr(s)) # 'Python'
print(s[0], s[4]) # P o
cnt = 0
for d in dir(s):
cnt += 1
print(d, end=', ')
if cnt % 5 == 0:
print()
# __add__, __class__, __contains__, __delattr__, __dir__,
# __doc__, __eq__, __format__, __ge__, __getattribute__,
# __getitem__, __getnewargs__, __gt__, __hash__, __init__,
# __init_subclass__, __iter__, __le__, __len__, __lt__,
# __mod__, __mul__, __ne__, __new__, __reduce__,
# __reduce_ex__, __repr__, __rmod__, __rmul__, __setattr__,
# __sizeof__, __str__, __subclasshook__, capitalize, casefold,
# center, count, encode, endswith, expandtabs,
# find, format, format_map, index, isalnum,
# isalpha, isascii, isdecimal, isdigit, isidentifier,
# islower, isnumeric, isprintable, isspace, istitle,
# isupper, join, ljust, lower, lstrip,
# maketrans, partition, replace, rfind, rindex,
# rjust, rpartition, rsplit, rstrip, split,
# splitlines, startswith, strip, swapcase, title,
# translate, upper, zfill,
# index()와 find()의 차이점
# print(s.index('p')) # ValueError: substring not found
print(s.find('p')) # -1
print('python'.isalpha()) # True
print('python3'.isalpha()) # False --> 3이 있기 때문
print('python3'.isalnum()) # True
print('python 3'.isalnum()) # False --> 공백
print('3'.isdecimal()) # True --> 0 ~ 9 숫자
print('234'.isdecimal()) # True
print('3'.isdigit()) # True
print('3'.isnumeric()) # True
print('3.3'.isdecimal()) # False
s = '3\u00B2' # 유니코드
print(s) # 3² 제곱근
print(s.isdecimal()) # False
print(s.isdigit()) # True
print(s.isnumeric()) # True
s = '\u00BC'
print(s) # ¼ 분수
print(s.isdecimal()) # False
print(s.isdigit()) # False
print(s.isnumeric()) # True
s = 'Python'
print(s.islower()) # False
print(s.isupper()) # False
s2 = s.replace('P', 'p')
print(s, s2) # Python python
print(s2.islower()) # True
s = 'I like Python.'
s3 = s.split()
print(s3) # ['I', 'like', 'Python.']
s = 'I like Python\nYou like Python'
sline = s.splitlines() # \n 기준으로 split
print(sline) # ['I like Python', 'You like Python']
print(sline[0].upper()) # I LIKE PYTHON
print(sline[1].lower()) # you like python
print(s.count('like')) # 2
■ format & print
data = 4321.1234567890123
print('DATA={:.2f}'.format(data)) # DATA=4321.12
print('DATA={:8.2f}'.format(data)) # DATA= 4321.12
print('DATA={:,}'.format(data)) # DATA=4,321.123456789012
print('DATA={:,.2f}'.format(data)) # DATA=4,321.12
print('DATA={:d}'.format(int(data))) # DATA=4321
print('DATA={:e}'.format(data)) # DATA=4.321123e+03
■ json & pickle - dump load
# text 파일을 한 줄 한 줄이 아닌 리스트 전체 저장을 위해 json 사용
import json
data = ['String 1', 'String 2', 'String 3']
f = open('files.txt', 'w')
json.dump(data, f) # files.txt에 data(['String 1', 'String 2', 'String 3']) 저장
f.close()
f = open('files.txt', 'r')
x = json.load(f)
print(x) # ['String 1', 'String 2', 'String 3']
f.close()
## 대용량 데이터 size 줄이는 binary 데이터로 저장 - pickle
import pickle
data = ['String 1', 'String 2', 'String 3']
f = open('files_bi.txt', 'wb')
pickle.dump(data, f)
f.close()
f = open('files_bi.txt', 'rb')
x = pickle.load(f)
print(x)
f.close()
[출처] https://www.youtube.com/watch?v=8_VWnRvbGPs Python Standard Lib 부분
'코딩 연습 > 코딩배우기' 카테고리의 다른 글
[Python] 파이썬 기본기 UP - 함수, 클래스, DB 다루기 (0) | 2021.07.20 |
---|---|
12 간지 띠 알아보기 (파이썬 기초 예제) (0) | 2021.07.18 |
[Python] 파이썬을 활용한 업무자동화 - 이메일 보내기 받기 연습 코드 정리 (0) | 2021.07.09 |
[Python] 파이썬으로 이메일 리스트(엑셀) 불러와서 email 정상 여부 체크하기 (re 정규식과 openpyxl 사용) (0) | 2021.07.09 |
[Python] 파이썬을 활용한 업무자동화 - 웹 자동화(iframe 스크래핑, Web Element, 동적페이지 스크래핑) 연습 코드 정리 (0) | 2021.07.07 |
댓글