IT

파이썬 활용

rimicode 2022. 6. 10. 21:07
728x90
반응형
SMALL

정규표현식

정규표현식과 같이 프로그래밍에서 범용적으로 쓰이는 기술들은 프로그래밍 언어나 특정 기술에 종속되지 않고 쓰이기 때문에 익숙해져야 할 중요한 방법 중 하나

특정한 규칙을 가진 문자열의 집합을 표현하는데 사용하는 형식 언어

파이썬에서는 표준 라이브러리를 통헤 제공

정규표현식은 검색 엔진, 워드 프로세서와 문서 편집기의 찾아 바꾸기 대화상자, sed, AWK와 같은 문자 처리 유틸리티, 어휘 분석에 사용

# 정규표현식 라이브러리
import re

wordlist = ['color', 'colour', 'work', 'working', 'fox']

for word in wordlist:
	if re.search('col.r', word):
		print(word)

# color
# case
phone = re.compile('010-\d{4}-\d{4}')
info = ['짱구 010-1234-5678', '맹구 010-9876-5432']

for text in info:
	match_object = phone.search(text)
    print(match_object.group())

# 010-1234-5678
# 010-9876-5432

 


escape 문자

이스케이프 문자 이름
\n 줄 바꿈
\t
\b 백스페이스
\\ 백슬래시 ( \ )
\' 작은 따옴표 ( ' )
\" 큰 따옴표 ( " )

\r escape 문자는 현재 활성 위치를 현재 라인의 시작 위치로 옮기는 역할

print('     \rHello')
print('     Hello')

# Hello
#      Hello

두 print 문 모두 앞에 다섯 칸 공백

\r 을 사용하면 현재 위치에서 커서를 맨 앞으로 이동시키기 때문에 앞의 공백에 제거


raw string

파이썬 string은 \n과 같은 escape 문자를 특수문자로 인식하여 줄바꿈으로 작동

문자열 그대로 사용하고자 한다면 raw string 사용

출력할 문자열 앞에 r을 붙여주면 raw string 을 나타내며, 문자열 내용이 그대로 출력

json, html과 같은 문서와 파일 경로에서 슬래시( \ )가 자주 사용되는데, 이때 문자열 그대로 사용하고자 할 때 주로 사용

print('C:\programs\nayana')
print('C:\\programs\\nayana')
print(R'C:\programs\nayana')

# C:\programs
# ayana
# C:\programs\nayana
# C:\programs\nayana

rjust(width, [fillchar])

원하는 문자를 따로 지정하고, 다른 문자열로 앞 부분을 채워줄 수 있다.

print("2".rjust(3, "0"))
print("50000".rjust(5, "0"))
print("123".rjust(5, "0"))
print("123".rjust(5, "a"))

# 002
# 50000
# 00123
# aa123

zfill(width)

print("2".zfill(3))
print("50000".zfill(5))
print("123".zfill(5))

# 002
# 50000
# 00123

Split

string = "Hello, I am Jack and I am a data scientist"
print(string)
print(string[1])

# Hello, I am Jack and I am a data scientist
# e
string_list = string.splint(" ")
string_list

# ['Hello', 'I', 'am', 'Jack', 'and', 'I', 'am', 'a', 'data', 'scientist']
string.startswith('Hello')

# True
string.endswith('scientist')

# True
string.endswith('tist')

# True
print(string.replace("Jack", "John"))
print(string)

# Hello, I am John and I am a data scientist
# Hello, I am Jack and I am a data scientist

얕은 복사(copy())

animals = {"mouse", "cow", "tiger"}
animals_copy = animals.copy()
animals_copy

# {'cow', 'mouse', 'tiger'}
a = {'a': 2, 'b': 6, 'c': 7}
b = a
del b['a']
print(b)
print(a)

# {'b': 6, 'c': 7}
# {'b': 6, 'c': 7}
import copy
a = {'a': 2, 'b': 6, 'c': 7}
b = copy.copy(a)
del b['a']
print(b)
print(a)

# {'b': 6, 'c': 7}
# {'a': 2, 'b': 6, 'c': 7}

깊은 복사(deep copy)

내부 객체들까지 새롭게 copy

완전히 새로운 변수를 만드는 것

import copy
list_var = [[1,2],[3,4]]
list_var_deepcopy = copy.deepcopy(list_var)
list_var_copy = list_var.copy()

list_var[1].append(5)

print(list_var)  # 원래 변수

print(list_var_deepcopy)  # deepcopy : append와 같은 메소드를 써도 값이 변경되지 않음

print(list_var_copy)  # copy : 원본이 변경되었으므로 함께 변경됨

# [[1, 2], [3, 4, 5]]
# [[1, 2], [3, 4]]
# [[1, 2], [3, 4, 5]]

반복문과 조건문

범위 경계 테스트 반드시 하기!

print 해서 값이 어떻게 나오는지 확인

상황에 적합한 반복문 활용

data = [20, 22, 27, 60]
for i in range(len(data)):
   print(data[i])
   
# 20
# 22
# 27
# 60
mock_data = {
  "id": 1,
  "first_name": "길동",
  "last_name": "홍",
  "email": "123@naver.com",
  "gender": "Female",
  "ip_address": "123.456.789.01"
}

for x in mock_data:
    print(x)

# id
# first_name
# last_name
# email
# gender
# ip_address
for x in mock_data.keys():
    print(x)
    
# id
# first_name
# last_name
# email
# gender
# ip_address
for x in mock_data.values():
    print(x)
    
# 1
# 길동
# 홍
# 123@naver.com
# Female
# 123.456.789.01
for x in mock_data.items():
    print(x)
    
# ('id', 1)
# ('first_name', '길동')
# ('last_name', '홍')
# ('email', '123@naver.com')
# ('gender', 'Female')
# ('ip_address', '123.456.789.01')
for k,v in mock_data.items():
    print(k,v)
    
# id 1
# first_name 길동
# last_name 홍
# email 123@naver.com
# gender Female
# ip_address 123.456.789.01

 

# 일반적인 반복문
a = [1,2,3,4,5]
b = [10,20,30,40,50]
for i in range(len(a)):
   print(a[i],b[i])
   
# 1 10
# 2 20
# 3 30
# 4 40
# 5 50
# zip 함수
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = zip(a,b)
print(list(c))

# [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)]
# 반복문과 zip
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = [100,200,300,400,500]
for x,y,z in zip(a,b,c):
   print(x,y,z)
   
# 1 10 100
# 2 20 200
# 3 30 300
# 4 40 400
# 5 50 500
# break
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
    if(x==3):
        break
    else:
        print(x)
        
# 0
# 1
# 2
# continue
IntCollection=[0,1,2,3,4,5,6,7]
for x in IntCollection:
    if(x==3):
        continue
    else:
        print(x)
        
# 0
# 1
# 2
# 4
# 5
# 6
# 7
# 반복문 활용
list_ = [1,2,3,4,5]

def foo(list_):
  print(list_)

print('foo(list_[i])')
for i in range(len(list_)):
    foo(list_[i])

print('foo(element)')
for element in list_:
    foo(element)
    
# foo(list_[i])
# 1
# 2
# 3
# 4
# 5
# foo(element)
# 1
# 2
# 3
# 4
# 5

Error & Wraning

# IndentationError
def print_list(list):
for item in list: # 에러 확인 및 해결필요
print(item)

#   File "<ipython-input-53-c923786c7daf>", line 2
#     for item in list: # 에러 확인 및 해결필요
#       ^
# IndentationError: expected an indented block
# SyntaxError
123ddf

#   File "<ipython-input-54-0886e53a92e9>", line 1
#     123ddf
#          ^
# SyntaxError: invalid syntax
# KeyboardInterrupt
while True:
  pass
  
# KeyboardInterrupt                         Traceback (most recent call last)
# <ipython-input-55-648a2bab0435> in <module>()
#       1 while True:
# ----> 2   pass
# 
# KeyboardInterrupt:
# TypeError
print(1) / 232

a,b = 0
print(a,b)

# 1
# ---------------------------------------------------------------------------
# TypeError                                 Traceback (most recent call last)
# <ipython-input-56-70486ff6f904> in <module>()
# ----> 1 print(1) / 232
#       2 
#       3 a,b = 0
#       4 print(a,b)
# 
# TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
# ZeroDivisionError
value = 2/0

# ZeroDivisionError                         Traceback (most recent call last)
# <ipython-input-57-457fed3f50f4> in <module>()
# ----> 1 value = 2/0
# 
# ZeroDivisionError: division by zero
# 경고(warning)
def A():
  a = 0
  c =0
  print(a,c,) 
  
# 경고는 명시적으로 보이지 않지만, 메모리 비효율/휴먼 에러 등 발생할 수 있음
728x90
반응형
LIST