4.0 Methods
Data structure(자료구조)를 사용하여 데이터 구조화에 대해 알아본다.
파이썬의 데이터 구조는 3가지가 있다.
list
tuple
dictionary
Data structure(자료구조)는 데이터를 구조화 하고 싶을 때 사용한다.
list에 대해 먼저 알아본다.
list는 variable 1개 안에 있어야 한다.
list를 만드려면 대괄호 [] 를 사용해야 한다.
데이터를 넣을 때는 쉼표를 사용해서 분리한다.
일반 variable 안에 넣은것과
list를 만들어서 넣은 것
days_of_week = "Mon,Tue,Wed,Thu,Fri"
print(days_of_week)
days_of_week2 = ["Mon","Tue","Wed","Thu","Fri"]
print(days_of_week2)
출력값:
Mon,Tue,Wed,Thu,Fri
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
위 둘의 차이점은 어떤걸까?
둘의 차이점을 알기 위해서 Method 를 알아야 한다.
. 을 이용해서 name 이라는 variable 에 모든 function 이 결합되어 있는걸 알수 있다.
name 은 string 이고, string 은 내부에 많은 fuction을 내포하고 있다.
정확히는 string 이나 number 나 같은 것들이 내부에 가지고 있는 function은
function이라고 하지 않고, method 라고 부른다.
function은 예를 들어 print, 이전에 만들었던 say_hello() , 이전에 import 했던 random fuction 도
function 의 종류다.
method 는 데이터 뒤에 결합/연결된 function이다.
method 중 upper 라는 method 를 사용해보자.
name ="minsoo" print(name.upper())
출력값:
MINSOO
name 이라는 variable 의 값인 minsoo 를
upper 라는 method 를 사용해서 대문자로 변환해주었다.
Python과 Python 안에 존재하는 데이터는 다 이런식이다.
다른 method를 사용해본다.
capitalize 라는 method 사용해본다.
name ="minsoo" print(name.capitalize())
출력값:
Minsoo
capitalize 는 앞문자를 대문자로 변환해주는 method 이다.
Variable 없이 데이터만 있어도 사용할 수 있다.
출력값은 똑같이 Minsoo 가 나온다.
print("minsoo".capitalize())
출력값:
Minsoo
data 에 결합되어 있는 이런 function들이 있다.
데이터가 있어야만 function 들이 실행될 수 있다.
이 fuction을 method 라고 한다.
데이터에 묶여있는 function
capitalize 라는 method든 ,어떤 method 든 데이터없이 단독으로 쓰일 수 없다.
number는 다른 종류의 결합된 function 을 가지고 있다.
string 도 다른 종류의 결합된 function 을 가지고 있다.
string에는 데이터를 변환, 조작 또 사용할 수 있는 결합된 function들이 있다.
startswith 라는 method를 사용해 본다.
name ="minsoo" print(name.startswith("m"))
출력값:
True
startswith 는 시작문자가 ( ) 안의 문자와 동일 한지 알려주는 method 이다.
정확히 말하면 어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 True 나 False 로 반환해준다.
replace라는 method를 사용해본다.
name ="minsoo" print(name.replace("o","u"))
출력값:
minsuu
replace라는 method 는 이전의 값을 새로운 값으로 대체해 주는 method 이다.
o → u 로 바꿔주었다.
python standard liabrary 를 보면 많은 method 들이 있다.
isupper 라는 method는 전체 문자열이 대문자인지 확인하여 True 나 False 로 반환해주는 method 이다.
print('banana'.isupper())
print('BANANA'.isupper())
print('baNana'.isupper())
출력값:
False
True
False
method 는 데이터에 결합된 function 이다.
예를 들어 print, input 등의 함수는 데이터에 결합되어 있지 않는다.
우리가 쓰고 싶을 때 어디에서나 쓸 수 있는 function 이다.
print("minsoo".endswith("o"))
endswith은 텍스트가 () 안의 문자열로 끝나는지 물어보는 method 이다.
endswith 는 string 과 결합되어 있는 function 이다. → method
endswith 단독으로는 사용할 수 없다. 작동하지 않는다.
'Programming > Python 웹 스크래퍼 만들기' 카테고리의 다른 글
Python Tuple, Dictionary (0) | 2022.11.09 |
---|---|
Python List (0) | 2022.11.08 |
Python while 문 사용해서 랜덤 숫자 맞추기 (0) | 2022.11.04 |
Python 랜덤 숫자 맞추기 (0) | 2022.11.03 |
Python if, elif, else 조건문 (0) | 2022.11.02 |