Python 타입별 메소드 정리

2023. 4. 17. 22:04language/Python

1. 문자열 메소드

더보기
# 1.count: 문자열 내에서 특정문자가 몇 개나 있는지 세는 메소드
text = "I study at home 12 hours a day"
ijh = text.count("a")
print(ijh)  # 3

# 2. find: 문자열 내에서 특정 문자열이 처음 나오는 위치를 찾아주는 메소드 (없을 경우 -1 return)
text = "I study at home 12 hours a day"
ijh = text.find("home")
print(ijh)  # 11

# 3. index: 문자열 내에서 특정 문자열이 처음 나오는 위치를 찾아주는 메소드 (없을 경우 VallueError) 
text = "I study at home 12 hours a day"
try:
    ijg = text.index("home")
    print(ijh)
except ValueError:
    print("찾는 문자열이 없습니다.")

# 4. join: 특정 문자열을 기준으로 다른 문자열들을 합쳐주는 메소드
ijh = ["I", "Joo", "Han"]
joined_ijh = ", ".join(ijh)
print(joined_ijh)

# 5-1. upper: 문자열 내의 모든 알파벳 소문자를 대문자로 바꿔주는 메소드
# 5-2. lower: 문자열 내의 모든 알파벳 대문자를 소문자로 바꿔주는 메소드
text = "I study at home 12 hours a day"
uppercase_text = text.upper()
print(uppercase_text)

lowercase_text = text.lower()
print(lowercase_text)

# 6. replace: 문자열 내에서 특정 문자열을 다른 문자열로 바꾸는 메소드
text = "I study at home 12 hours a day"
replaced_text = text.replace("study", "work out")
print(replaced_text)

# 7. split: 문자열을 특정 문자를 기준으로 나누는 메소드 (결과는 리스트 형태로 반환)
ijh = "I, Joo, Han"
ijh_list = ijh.split(",")
print(ijh_list)

 

2. 리스트 메소드

더보기
# 1. len: 리스트의 길이를 반환하는 내장 함수
ijh_1 = [1, 2, 3, 4, 5]
print(len(ijh_1))

# 2. del: 리스트에서 특정 요소를 삭제하는 연산자
ijh_2 = [1, 2, 3, 4, 5]
del ijh_2[2]
print(ijh_2)

# 3. append: 리스트의 맨 뒤에 새로운 요소를 추가하는 메소드
ijh_3 = [1, 2, 3, 4, 5]
ijh_3.append(6)
print(ijh_3)

# 4. sort: 리스트를 오름차순으로 정렬하는 메소드
ijh_4 = [1, 2, 3, 4, 5]
ijh_4.sort()
print(ijh_4)

# 5. reverse: 리스트의 요소 순서를 반대로 뒤집는 메소드
ijh_5 = [1, 2, 3, 4, 5]
ijh_5.reverse()
print(ijh_5)

# 6. index: 리스트에서 특정 요소의 인덱스를 반환하는 메소드
ijh_6 = ['I', 'Joo', 'Han']
print(ijh_6.index('Joo'))

# 7. insert: 리스트의 특정 위치에 요소를 삽입하는 메소드
ijh_7 = [1, 2, 3, 4, 5]
ijh_7.insert(2, 10)
print(ijh_7)

# 8. remove: 리스트에서 특정요소를 제거하는 메소드
ijh_8 = [1, 2, 3, 4, 5]
ijh_8.remove(3)
print(ijh_8)

# 9. pop: 리스트에서 마지막 요소를 빼낸뒤, 그 요소를 삭제하는 메소드 
ijh_9 = [1, 2, 3, 4, 5]
ijh_9.pop(3)
print(ijh_9)

# 10. conut: 리스트에서 특정요소의 개수를 세는 메소드
ijh_10 = [1, 2, 3, 3, 4, 5]
print(ijh_10.count(3))

# 11-1. extend: 리스트를 확장하여 새로운 요소들을 추가하는 메소드
# 11-2. +=: extend는 '+='을 사용하여 구현 할 수도 있음. 
ijh_11 = [1, 2, 3]
ijh_11.extend([4, 5, 6])
print(ijh_11)

ijh_12 = [1, 2, 3]
ijh_12 += [4, 5, 6]
print(ijh_12)

 

3. 딕셔너리 메소드

더보기
# 1. 딕셔너리 초기화
empty_dict = {}
ijh_dict_1 = {"Samsung": 1, "Microsoft": 1, "Apple": 4}
print(ijh_dict_1)

# 2. 딕셔너리 쌍 추가
ijh_dict_2 = {"Samsung": 1, "Microsoft": 1, "Apple": 4}
ijh_dict_2["LG"] = 1
print(ijh_dict_2)

# 3. del: 딕셔너리에서 특정 요소를 삭제
ijh_dict_3 = {"Samsung": 1, "Microsoft": 1, "Apple": 4}
del ijh_dict_3["Apple"]
print(ijh_dict_3)

# 4. 딕셔너리에서 특정 Key에 해당하는 Value를 얻는 방법(딕셔너리에 Key가 업는 경우. KeyError)
ijh_dict_4 = {"Samsung": 1, "Microsoft": 1, "Apple": 4}
print(ijh_dict_4["Apple"])

# 5. Keys: 딕셔너리에서 모든 Key를 리스트로 만들기
ijh_dict_5 = {"Samsung": 1, "Microsoft": 1, "Apple": 4}
ijh_list_1 = list(ijh_dict_5.keys())
print(ijh_list_1)

# 6. Values: 딕셔너리에서 모든 Key를 리스트로 만들기
ijh_dict_6 = {"Samsung": 1, "Microsoft": 1, "Apple": 4}
ijh_list_2 = list(ijh_dict_6.values())
print(ijh_list_2)

# 7. items: 딕셔너리의 모든 Key와 Value값을 튜플 형태 리스트로 반환
ijh_1 = {"name": "I Joo Han", "age": 30, "gender": "male"}
ijh_info = ijh_1.items()
print(ijh_info)

# 8. clear: 딕셔너리의 모든 요소를 삭제
ijh_2 = {"name": "I Joo Han", "age": 30, "gender": "male"}
ijh_2.clear()
print(ijh_2)

# 9. get: 딕셔너리에서 지정한 Key에 대응하는 값을 반환 (딕셔너리에 Key가 없는 경우, None 반환)
ijh_3 = {"name": "I Joo Han", "age": 30, "gender": "male"}
name = ijh_3.get("name")
print(name)

email = ijh_3.get("email")
print(email)

email = ijh_3.get("email", "unknown") # 기본값을 설정할 수 있음
print(email)

# 10. in: 해당 Key가 딕셔너리 안에 있는지 확인
ijh_4 = {"name": "I Joo Han", "age": 30, "gender": "male"}
print("name" in ijh_4)
print("email" in ijh_4)

 

Django에서 request.POST['key'] 와 request.POST.get('key') 의 공통점 & 차이점

더보기
  • 공통점
    • 두 방식 모두 딕셔너리에서 'key'에 해당하는 데이터를 가져옵니다.
  • 차이점
    • request.POST['key']: key가 존재하지 않을 경우 KeyError를 출력하는 예외가 발생합니다.
    • request.POST.get['key']: key가 존재하지 않을 경우 None을 반환하며, None대신 반환할 디폴트 값을 지정할 수 있습니다.