행위

파이썬 입문

DB CAFE

Dbcafe (토론 | 기여)님의 2020년 12월 3일 (목) 15:53 판 (문자열 조작 함수)
thumb_up 추천메뉴 바로가기


목차

1 파이썬 기본기 다지기[편집]

2 참고 url[편집]

파이썬 언어 기본 for Finance https://www.notion.so/for-Finance-355667aea8f34c169cd7c0f705aaa875

[PY4E] 모두를 위한 프로그래밍 : 파이썬 https://www.notion.so/PY4E-7573a4454709441fa035d5237163aff0

3 데이터 타입[편집]

# int 
>>> a = 3
>>> type(a)
int
  1. float
  2. str
  3. bool
  4. complex
>>> c = 3 + 4j
>>> type(c)
complex

4 데이터 구조체[편집]

4.1 리스트 (LIST)[편집]

파이썬에는 배열은 없으며 대신에 index를 부여할 수 있는 시퀀스 타입을 제공. 파이썬에서 시퀀스 타입의 특징은 저장하고 있는 데이터가 순서를 가진다는 점이며, 그 중 하나가 list 타입. 배열과 거의 흡사하다고 볼수 있다.

  1. list에 담을 수 있는 타입에는 제한이 없음
    1. 정수, 문자열 등의 타입뿐만 아니라 모든 타입의 객체 및 다른 list 객체
      my_list = [1, 'hello', 3.7, [7, 8, 9], {"a": 2, "b": 3}]

4.1.1 생성[편집]

>>> names = [ ]
>>> names = ['a', 'b', 'c', 'd, 'e']

또는

>>> names  = list()
>>> names.append('a')
>>> names.append('b')

4.1.2 인덱싱 (indexing)[편집]

>>> names = ['a', 'b', 'c', 'd, 'e']
>>> names[0]
'a'
>>> names[1]
'b'

4.1.3 append (리스트 뒤에 추가)[편집]

>>> names = ['a', 'b','c']
>>> names.append('d')
>>> names
['a', 'b', 'c', 'd']

>>> my_list = [1, 3, 5]
>>> my_list.append(100)
>>> my_list
[1, 3, 5, 100]
>>> my_list.append([200, 300])
>>> my_list
[1, 3, 5, 100, [200, 300]]

4.1.4 insert (특정위치에 추가)[편집]

>>> names = ['a', 'b', 'c']
>>> names.insert(1, 'e')
>>> names
['a', 'e', 'b', 'c']

4.1.5 확장 (extend)[편집]

list 객체에 새로운 list를 더하여 확장. 이때 extend(x) 에서 x에는 iterable을 구현한 객체만 사용 가능한데, 시퀀스 타입의 자료형들은 모두 iterable을 구현했으므로 사용 가능. append(x) 와의 차이점은 append()는 하나의 요소로서 추가되지만 extend()는 확장 개념으로 추가된다는 점. 똑같은 list를 추가해보면 바로 차이점을 알 수 있음.

>>> my_list = [1, 3, 5]
>>> my_list.extend([100, 200, 300])
>>> my_list
[1, 3, 5, 100, 200, 300]

4.1.6 요소 제거 (remove)[편집]

>>> my_list = [1, 3, 1, 3]
>>> my_list.remove(1)
>>> my_list
[3, 1, 3]
>>> my_list.remove(3)
>>> my_list
[1, 3]

또는 DEL 키워드 사용

>>> my_list = [1, 3, 1, 3]
>>> del my_list[1]
>>> my_list
[1, 1, 3]

4.1.7 list 값 꺼내기 (pop)[편집]

list의 요소 중 끝의 요소를 꺼내어 반환. 복사가 아닌 꺼내는 것이기 때문에 꺼낸 요소는 list 객체에서 사라짐.

>>> my_list = [1, 3, 1, 3]
>>> my_list.pop()
3
>>> my_list
[1, 3, 1]

pop(index) 로 사용하면 index 위치의 요소 값을 꺼냅니다.

>>> my_list = [1, 3, 1, 3]
>>> my_list.pop(1)
3
>>> my_list
[1, 1, 3]

4.1.8 list 정렬 (sort)[편집]

list의 요소 값들을 오름차순으로 정렬.

>>> my_list = [1, 3, 1, 3]
>>> my_list.sort()
>>> my_list
[1, 1, 3, 3]

내림차순으로 정렬하는 경우는 reverse 값을 True.

>>> my_list = [1, 3, 1, 3]
>>> my_list.sort(reverse=True)
>>> my_list
[3, 3, 1, 1]

4.1.9 list 거꾸로 뒤집기 (reverse)[편집]

list의 요소를 거꾸로.

>>> my_list = [1, 2, 3, 4]
>>> my_list.reverse()
>>> my_list
[4, 3, 2, 1]

4.1.10 len(s)[편집]

>>> names = ['a', 'b', 'c', 'd, 'e']
>>> len(names)
5

4.1.11 COUNT list 특정 값 개수 카운트[편집]

>>> my_list = [1, 2, 3, 4, 1, 2, 3, 4]
>>> my_list.count(1)
2

4.1.12 comprehension[편집]

  • 컴프리핸션: 리스트를 한줄의 코드로 쉽게 만들때 사용
>>> data = [3, 4, 5]
>>> float_data = [float(d) for d in data]

4.1.13 문자열을 리스트로 형변환[편집]

>>> my_str = 'python'
>>> my_list = list(my_str)
>>> my_list
['p', 'y', 't', 'h', 'o', 'n']

4.1.14 다차원 리스트[편집]

파이썬에서는 모든 것들이 객체이기 때문에 변수에 무엇을 집어넣든지 실제 그 객체가 들어가는 것이 아닌 객체를 가리키는 객체의 참조 주소값이 변수에 할당됩니다. 그런 의미로 list의 요소들도 사실은 실제 값이 아닌 요소에 할당된 객체의 주소를 가리키고 있습니다.


따라서 위의 개념처럼 다차원 list를 만들게 되면 또 다른 list가 생성되고 그 list의 주소값을 요소로 가지고 있는 것입니다. 위의 그림은 쉬운 이해를 위해 쉽게 표현한 것입니다.(실제로는 나머지 요소들도 실제 정수 값이 아닌 정수 객체를 가리키는 주소값이 들어가 있습니다.)

>>> my_list = [1, 3, 5, [11, 13, 15]]
>>> my_list
[1, 3, 5, [11, 13, 15]]
>>> my_list[3]
[11, 13, 15]

4.1.15 리스트 요소에 index 범위로 접근[편집]

파이썬에서 list같은 시퀀스 타입 자료구조의 장점은 다양한 방법으로 요소들을 접근할 수 있다는 점. 데이터를 다루는데, 매우 유연하게 코드를 작성할 수 있으며, 머릿속에 생각한대로 직관적으로 데이터를 다룰 수 있음.

>>> my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 
>>> my_list[9:]  # [9]부터 이후의 모든 요소
[10, 11, 12] 
>>> my_list[:4]   # [4] 이전의 모든 요소
[1, 2, 3, 4] 
>>> my_list[::3]  # 요소를 3씩 건너 뛰며 접근
[1, 4, 7, 10] 
>>> my_list[1:5]  # [1] 부터 [5] 이전까지
[2, 3, 4, 5] 
>>> my_list[3::2]  # [3] 부터 2씩 건너 뛰며 접근
[4, 6, 8, 10, 12]

4.1.16 list객체 + 연산[편집]

>>> my_list = [1, 3, 5, 7, 9]
>>> my_list = my_list + my_list
>>> my_list
[1, 3, 5, 7, 9, 1, 3, 5, 7, 9]

4.1.17 list객체 * 연산[편집]

>>> my_list = [1, 3, 5, 7, 9]
>>> my_list * 3
[1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9]

4.1.18 list 요소 값 부분 수정[편집]

>>> my_list = [1, 3, 5, 7, 9]
>>> my_list[3] = 10
>>> my_list
[1, 3, 5, 10, 9]

4.1.19 list 요소 인덱스 범위 연산으로 수정[편집]

리스트[시작:끝] 범위연산을 같이 사용하면 한꺼번에 값을 수정할 수 있음. 주의할점은 my_list[3] = [1,2] 와 같은 식으로 수정하려 하면 범위 수정이 아닌 [3] 요소에 [1,2] list가 들어가서 [1, 3, 5, [1, 2], 9] 과 같이 2차원 list가 되어버린다는 점. [0:3]은 [0], [1], [2] 를 의미하므로 해당 범위를 수정하기 위해 삭제

4.2 튜플[편집]

4.2.1 생성[편집]

>>> names = ('a', 'b', 'c', 'd, 'e')

4.2.2 len(s)[편집]

>>> names = ('a', 'b', 'c', 'd, 'e')
>>> len(names)
5

4.2.3 indexing[편집]

>>> names = ('a', 'b', 'c', 'd, 'e')
>>> names[0]
'a'
>>> names[1]
'b'

4.3 딕셔너리[편집]

4.3.1 생성[편집]

>>> cur_price = { }

4.3.2 insert[편집]

>>> cur_price['samsung'] = 10000
>>> cur_price
{'samsung': 10000}

4.3.3 indexing[편집]

>>> cur_price['samsung']
>>> 10000

4.3.4 delete[편집]

>>> del cur_price['samsung']
>>> cur_price{}

4.3.5 key, value[편집]

>>> cur_price.keys()
dict_keys(['samsung'])
>>> cur_price.values()
dict_values([10000])

5 기본 함수[편집]

5.1 print[편집]

5.2 다중 변수 print[편집]

print("City", city, 'is in the country', country)

5.2.1 값을 매개 변수로 전달[편집]

print("City {} is in the country {}".format(city, country))

5.2.2 문자열 형식 사용[편집]

순차적 옵션

print("City {} is in the country {}".format(city, country))

숫자 서식

print("City {1} is in the country {0}, yes, in {0}".format(country, city))

명시 적 이름으로 형식화

print("City {city} is in the country {country}".format(country=country, city=city))

5.2.3 튜플로 인수를 전달[편집]

print("City %s is in the country %s" %(city, country))

5.2.4 Only from Python 3.6[편집]

print(f"City {city} is in the country {country}".format(country=country, city=city))

6 문자열 조작 함수[편집]

6.1 len(s)[편집]

>>> mystring = "hello world"
>>> len(mystring)
11
Python-slicing.jpg

6.2 indexing[편집]

>>> mystring[0]
'h'

6.3 slicing[편집]

>>> mystring[0:5]
'hello'

>>> mystring[6:]
'world'

6.4 문자열.split(S)[편집]

>>> companies = "yahoo google"

>>> companies.split(' ')
['yahoo', 'google']

6.5 in[편집]

>>> 'google' in companies
True

6.6 combining[편집]

>>> s1 = "hello"
>>> s2 = "world"
>>> s3 = s1 + ' ' + s2
>>> s3
"hello world"

6.7 replace[편집]

>>> a = "yahoo;google"
>>> new_a = a.replace(';', '-')
>>> new_a
"yahoo-google"

6.8 index[편집]

>>> s = "yahoo google"
>>> s.index("google")
6

6.9 문자열.find(x)[편집]

>>> s = "yahoo google"

>>> s.find("google")
6

6.10 stripping[편집]

>>> a = "  yahoo  "
>>> new_a = a.strip()
>>> new_a
"yahoo"

6.11 데이터 형변환[편집]

다음과 같이 데이터를 다른 자료형으로 Casting 할 수 있다.

>>> float(3)    #실수형으로 바꿈
3.0
>>> int(3.0)    #정수형으로 바꿈
3
>>> int('0xc', 16)
>>> int('0o14', 8)
두 번째 인자에 입력 값의 진수를 명시하면 된다. 다른 벡터 형으로 변환할 수도 있다.

>>> str(3)  #문자열로 바꿈
'3'
>>> hex(12) #16진수로 바꿈
'0xa'
>>> oct(10) #8진수로 바꿈
'0o12'
>>> bin(10) #2진수로 바꿈
'0b1010'
다시 10진수로 바꿀 때는 자동으로 바뀐다.

>>> tuple([1,2])    #리스트를 튜플로 바꿈
(1, 2)
>>> list((1,2)) #튜플을 리스트로 바꿈
[1, 2]
>>> set([1,2])  #리스트를 집합 데이터형으로 바꿈
{1, 2}

7 딕셔너리로 캐스팅[편집]

딕셔너리로 캐스팅 하는 것은 조금 까다로운데 key 값을 어떻게 설정할 것인가를 정해야 하기 때문. key와 value가 한 쌍으로 된 경우 딕셔너리로 캐스팅 할 수 있다.

>>> dict([[1,2],[3,4]])#쌍으로 된 경우만 딕셔너리형으로 변환된다.
{1: 2, 3: 4}

7.1 유니코드로 변환[편집]

>>> ord(‘가’)    #문자를 유니코드 값으로 변환
44032   #44032는 ‘가’의 유니코드 값
>>> chr(44032). #chr()함수는 유니코드 값을 문자로 변환한다.
‘가’

8 파이썬 제어문[편집]

8.1 조건별 분기[편집]

if ending_price > 10000:
    print("sell")
elif ending_price < 8000:
    print("buy")
else:
    print("hold")

8.2 반복 처리[편집]

  • Loop – For
>>> for i in range(0, 5):
        print(i)

0
1
2
3
4
>>> for i in range(0, 5):
        if i % 2 == 0:
            print(i, end=' ')
0, 2, 4
>>> buy_list = ['000660', '039490']
>>> for code in buy_list:
        print("buy", code)

buy 000660
buy 039490
>>> hold_list = {'naver': 10, 'samsung': 20}
>>> for company, num in hold_list.items():
        print(company, num)

naver 10
samsung 20

8.3 Loop - While[편집]

>>> i = 0
>>> while i < 5:
        print(i)
        i += 1

0
1
2
3
4
>>> i = 0
>>> while i < 5:
        if i % 2 == 0:
print(i)
        i += 1

0 2 4

9 파이썬 모듈 임포트 방법[편집]

  • 일반적인 import 방식
import os
  • 필요 함수만 import 하는 방식
from os import xxx
  • 모든 함수를 import 하는 방식
from os import *

10 변수[편집]

Python-var.jpg
>>> a = 10
>>> id(a)

11 함수 선언[편집]

>>> def cal_upper_price(price):
        increment = price * 0.3
        upper_price = price + increment
        return upper_price

>>> upper_price = cal_upper_price(10000)
>>> upper_price
13000

12 모듈[편집]

# stock.py
def cal_upper_price(price):
    increment = price * 0.3
    upper_price = price + increment
    return upper_price
  • stock.py 모듈 import
# test.py
import stock
upper_price = stock.cal_upper_price(10000)
  • stock.py 모듈 import
# test.py
from stock import *
upper_price = upper_price(10000)

13 클래스[편집]

  • 클래스 정의(Class Definitions)
    • Class: 인스턴스의 청사진 , a blueprint for an instance ("instance factories")
    • Instance: 클래스의 생성된 객체 , a constructed object of the class
    • Type: 인스턴스가 속한 (타입별)클래스를 가르킴 , indicates the class the instances belong to
    • Attribute: 모든 객체 값 ,any object value: object.attribute
    • Method: 클래스에 선언된 호출 가능한 속성 , a "callable attribute" defined in the class

13.1 인스턴스 메소드[편집]

class Joe:
    def callme(self):
        print("calling 'callme' method with instance")

thisjoe = Joe() #인스턴스 할당
thisjoe.callme() #메소스 호출

13.2 클래스 정의[편집]

class BusinessCard:
    def __init__(self, name, email):
        self.name = name
        self.email = email

    def print_info(self):
        print(self.name)
        print(self.email)
# instantiation and call the method
mem1 = BusinessCard("Goo", "goo@gmail.com")
mem1.print_info()

13.3 클래스 상속[편집]

  • Class – Inheritance
>>> class Parent:
        def can_sing(self):
            print("sing a song")

>>> father = Parent()
>>> father.can_sing()
sing a song


>>> class LuckyChild(Parent):
        pass

>>> child1 = LuckyChild()
>>> child1.can_sing()
sing a song

>>> class LuckyChild2(Parent):
       def can_dance(self):
          print("dance beautifully")

>>> child2 = LuckyChild2()
>>> child2.can_sing()
sing a song
>>> child2.can_dance()
dance beautifully

13.4 클래스 상속2[편집]

  • Class – Inheritance II
>>> class Parent:
        def __init__(self):
            self.money = 10000
        
>>> class Child1(Parent):
        def __init__(self):
            super().__init__()        

>>> class Child2(Parent):
        def __init__(self):
            pass
    
>>> child1 = Child1() #Parent의 __init__ 를 할당 받은경우 
>>> child2 = Child2() #받지 않은 경우 
>>> print(child1.money)
10000
>>> print(child2.money)
AttributeError: 'Child2' object has no attribute 'money'