코딩한걸음
728x90
반응형

Today I Learned


String Method

## string method

# count : 문자열 내에서 특정 문자가 몇 개나 있는지 셈
joonyeol = "Hellow, World"
count = joonyeol.count('l')
print(count) # 3


# find : 문자열 내에서 특정 문자열이 처음 나오는 위치를 찾아줌
# 없을 경우 -1 return
position = joonyeol.find("World")
print(position) # 8


# index : 문자열 내에서 특정 문자열이 처음 나오는 위치를 찾아줌
# 없을 경우 ValueError
try:
    position_2 = joonyeol.index("World")
    print(position_2) # 8
except ValueError:
    print("찾는 문자열이 없습니다.")


# join : 특정 문자열을 기준으로 다른 문자열들을 합쳐주는 메서드
fruits = ["apple", "banana", "cherry"]
joined_fruits = ", ".join(fruits)
print(joined_fruits) # apple, banana, cherry


# upper : 문자열 내에서 모든 소문자를 대문자로 바꾸는 메서드
# lower : 문자열 내에서 모든 대문자를 소문자로 바꾸는 메서드
uppercate_joonyeol = joonyeol.upper()
print(uppercate_joonyeol) # HELLOW, WORLD

lowercate_joonyeol = joonyeol.lower()
print(lowercate_joonyeol) # hellow, world


# replace : 문자열 내에서 특정 문자열을 다른 문자열로 바꾸는 메서드
replaced_joonyeol = joonyeol.replace("World", "Python")
print(replaced_joonyeol) # Hellow, Python


# split : 문자열을 특정 문자를 기준으로 나누는 메서드(결과는 리스트 형태로 반환)
fruits_split = joined_fruits.split(", ")
print(fruits_split) # ['apple', 'banana', 'cherry']

 


List Method

## list method

# len : 리스트의 길이를 반환하는 함수
joonyeol = [1, 2, 3, 4, 5]
print(len(joonyeol)) # 5


# del : 리스트에서 특정 인덱스를 삭제하는 연산자
del joonyeol[2]
print(joonyeol) # [1, 2, 4, 5]


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


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


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


# index : 리스트에서 특정 요소의 인덱스를 반환하는 메서드
joonyeol = ["apple", "banana", "cherry"]
print(joonyeol.index("banana")) # 1


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


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


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


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


# extend : 리스트를 확장하여 새로운 요소들을 추가하는 메서드
joonyeol = [1, 2, 3]
joonyeol.extend([4, 5, 6])
print(joonyeol) # [1, 2, 3, 4, 5, 6]


# += 연산자를 사용해서도 구현할 수도
joonyeol = [1, 2, 3]
joonyeol += [4, 5, 6]
print(joonyeol) # [1, 2, 3, 4, 5, 6]

 


Dictionary Method

## dictionary method

# 빈 딕셔너리 만들기
empty_joonyeol = {}
joonyeol = {"apple": 1, "banana":2, "orange":3}
print(joonyeol) # {'apple': 1, 'banana': 2, 'orange': 3}


# 딕셔너리 쌍 추가
joonyeol["grape"] = 4
print(joonyeol) # {'apple': 1, 'banana': 2, 'orange': 3, 'grape': 4}


# del : 딕셔너리에서 특정 요소를 삭제
joonyeol = {"apple": 1, "banana":2, "orange":3}
del joonyeol["apple"]
print(joonyeol) # {'banana': 2, 'orange': 3}


# 딕셔너리에서 특정 Key에 해당하는 Value를 얻는 방법 (딕셔너리에 Key가 없는 경우, KeyError)
joonyeol = {"apple": 1, "banana":2, "orange":3}
print(joonyeol["banana"]) # 2


# keys : 딕셔너리에서 모든 Key를 리스트로 만들기
joonyeol = {"apple": 1, "banana":2, "orange":3}
key_list = list(joonyeol.keys())
print(key_list) # ['apple', 'banana', 'orange']


# value : 딕셔너리에서 모든 Value를 리스트로 만들기
joonyeol = {"apple": 1, "banana":2, "orange":3}
value_list = list(joonyeol.values())
print(value_list) # [1, 2, 3]


# items : 딕셔너리의 모든키와 값을 튜플 형태의 리스트로 반환
joonyeol = {'name': 'joonyeol', 'age': 30, 'gender': 'male'}
items = joonyeol.items()
print(items) # joonyeol_items([('name', 'joonyeol'), ('age', 30), ('gender', 'male')])


# clear : 딕셔너리의 모든 요소를 삭제
joonyeol = {'name': 'joonyeol', 'age': 30, 'gender': 'male'}
joonyeol.clear()
print(joonyeol) # {}


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

email = joonyeol.get('email')
print(email) # None

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


# in : 해당 키가 딕셔너리 안에 있는지 확인
joonyeol = {'name': 'joonyeol', 'age': 30, 'gender': 'male'}
print('name' in joonyeol) # True
print('email' in joonyeol) # False

 


Process

from multiprocessing import Process
import os
## 프로세스 만들기
print('hello, os')
print('my pid is', os.getpid()) # my pid is 89784

def joonyeol():
    print('child process', os.getpid()) # child process 194140
    print('my parent is', os.getppid()) # my parent is 193068

if __name__ == '__main__':
    print('parent process', os.getpid()) # parent process 193068
    child = Process(target=joonyeol).start()


## 동일한 작업을 하는 프로세스 생성하기
def joonyeol():
    print('hello, os')

if __name__ == '__main__':
    child1 = Process(target=joonyeol).start() # hello, os
    child2 = Process(target=joonyeol).start() # hello, os
    child3 = Process(target=joonyeol).start() # hello, os


## 각기 다른 작업을 하는 프로세스 생성하기
def yoon():
    print('my name is yoon')

def joon():
    print('my name is joon')

def yeol():
    print('my name is yeol')

if __name__ == '__main__':
    child1 = Process(target=yoon).start() # my name is yoon
    child2 = Process(target=joon).start() # my name is joon
    child3 = Process(target=yeol).start() # my name is yeol

 


Thread

import threading
import os


## 코드로 스레드 만들기
def joonyeol():
    print('thread id', threading.get_native_id()) #thread id 197660
    print('process id', os.getpid()) # process id 197696

if __name__ == '__main__':
    print('process id', os.getpid()) # process id 197696
    thread = threading.Thread(target=joonyeol).start()


## 동일한 작업을 하는 스레드 생성하기
def joonyeol():
    print('thread id', threading.get_native_id())
    print('process id', os.getpid())

if __name__ == '__main__':
    print('process id', os.getpid())
    thread1 = threading.Thread(target=joonyeol).start()
    thread2 = threading.Thread(target=joonyeol).start()
    thread3 = threading.Thread(target=joonyeol).start()

#     # process id 198716
#     # thread id 194600
#     # process id 198716
#     # thread id 197272
#     # process id 198716
#     # thread id 197408
#     # process id 198716
#     # process는 같지만 thread는 다르다


## 각기 다른 작업을 하는 스레드 생성하기

def yoon():
    print('This is yoon')

def joon():
    print('This is joon')

def yeol():
    print('This is yeol')

if __name__ == '__main__':
    thread1 = threading.Thread(target=yoon).start()
    thread2 = threading.Thread(target=joon).start()
    thread3 = threading.Thread(target=yeol).start()

    # This is yoon
    # This is joon
    # This is yeol

 

선발대 숙제 끝 !

오랫만에 한줄한줄 쉐도우코딩하니깐 조금 답답했다.. 연습 자주 해야지

 

 

728x90
반응형
profile

코딩한걸음

@Joonyeol_Yoon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!