본문으로 바로가기

구글링 하면 다 나오지만 훑어볼 요량으로 적어보았다.

 

이걸 외운다는 건 어리석은 짓이다. 문서를 찾아보거나 구글링하는게 훨씬 편하다.

how to find an element in string python. 정도로 검색해봐도 원하는 게 바로 stoverflow에 나온다.

 

파이썬의 모든 자료형은 객체이다. 그래서 내장 함수도 꺼내 쓰고 하는 것이다.

 

문자열 관련 메서드

a = 'python for artificial intelligence'
b = ' hi '

# 문자열에 l이 몇 개 들어있니
print(a.count('l'))

# 첫번째로 y가 나온 인덱스
# The only difference is that find() method returns -1 if the substring is not found
# whereas index() throws an exception.
print(a.find('y'))
print(a.index('y'))

# 대문자화, 소문자화
print(a.upper())
print(a.lower())

# 문자열은 immutable하기 때문에 원본이 바뀌지는 않습니다.
print(a.replace("python", "javascript"))

# split한 문자열은 리스트에 담깁니다.
# ['python', 'for', 'artificial', 'intelligence']
print(a.split(' '))

# "|"를 문자열 a 사이에 넣어라.
# p|y|t|h|o|n| |f|o|r| |a|r|t|i|f|i|c|i|a|l| |i|n|t|e|l|l|i|g|e|n|c|e
print("|".join(a))

# strip
print(b.lstrip())
print(b.rstrip())
print(b.strip())

 

 

리스트 (리스트는 mutable함에 주의하자. 반면 튜플은 immutable하다.)

 

a = [1, 3, 5, ["life", "short"], 7, 9]

# 인덱싱, 슬라이스
print(a[0] + a[2])
print(a[-2])
print(a[1:2])
print(a[0::2])
print(a[3][0])

# CRUD. 리스트는 mutable하므로 원본이 변경된다.
a[0:2] = [16, 56]
print(a)

a[0:2] = []
print(a)

del a[0]
print(a)

a.append([3, 4])
# a.sort()
a.reverse()
a.index(7)
a.insert(0, [3, 4])
a.remove(3)
a.pop()

 

 

dict

a = {
    "name": "darren",
    "age": 23,
    "list": [1, 3, 5]
}

# 똑같음.
print(a["name"])
print(a.get("name"))

# CRUD
a["laptop"] = "thinkPad"
del a["laptop"]

# 자료형이 list가 아니라 dict_keys, dict_values라서 리스트 메서드 사용 불가
# list(a.keys()) 꼴로 리스트 변환 가능, 변환 안해도 iterate 구문은 사용 가능
print(a.keys())
print(a.values())

# key가 dict에 있니?
print('age' in a)

a.clear()

 

 

set

 

# 선언은 리스트나 문자열로
s1 = set([1, 3, 5])
s2 = set([2, 3, 4, 5])
s3 = set("whata")

print(s1)  # {1, 3, 5}
print(s3)  # {'a', 'w', 't', 'h'} 중복 불가, 순서 없음

# 교집합
Intersection = s1 & s2
print(Intersection)

# 합집합
union = s1 | s2
print(union)

# 차집합
difference = s1 - s2
print(difference)

s1.add(6)
s1.update([3, 4, 5])
s1.remove(4)


 

 

리스트 깊은 복사와 얕은 복사

 

리스트는 reference type이다. 따라서 얕은 복사본에 수정을 가하면 원본에도 수정이 가해진다. 깊은 복사를 하려면 copy 메서드를 사용하자

 

from copy import copy

a = [1, 3, 5]
b = a  # 얕은 복사
c = copy(a) # 깊은 복사
a[0] = 7

print(b)  [7, 3, 5]
print(c)  [1, 3, 5]

 

내장 함수들. lambda가 많이 쓰인다.

# 절댓값
abs(-5.6)

# 쓸 수 있는 메서드 출력
print(dir([]))

# (몫, 나머지)
print(divmod(10, 3))

# enumerate 인덱스와 원소 출력
for i, el in enumerate(['foo', 'da']):
    print(i, el)

# eval is evil
print(eval('3  + 5'))

# id 함수로 메모리 주소값 출력
a = 3
print(id(a))  # 메모리 주소값 출력
print(id(3))

# filter 함수
def is_positive(x): return x > 0

b = list(filter(is_positive, [-1, -3, 5, 7, 9]))
print(b)

# map 함수

def double_it(x): return x * 2

c = list(map(double_it, [3, 5, 7, 9]))
print(c)

# lambda

sum = lambda a, b: print(a + b)
sum(3, 4)

 

외장 함수

import os
import shutil
import time
import random

# 1 ~ 10 중 랜덤한 값 (10 포함)
print(random.randint(1, 10))

# 셔플(섞기)
test =[1, 3, 5]
random.shuffle(test)
print(test)

# 현재 경로 출력
print(os.getcwd())

# 명령창 청소
os.system("clear")

# new.txt를 copy.txt로 복사
shutil.copy("new.txt", "copy.txt")

# time 메서드.
print(time.time())
print(time.localtime(time.time()))
print(time.asctime(time.localtime(time.time())))

# time.asctime(time.localtime(time.time())) 와 같음
print(time.ctime())

 


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체