Daily Develope

[Python] 매칭 (문자열 / 리스트 / 정규식) 본문

Develope/Python

[Python] 매칭 (문자열 / 리스트 / 정규식)

noggame 2022. 1. 15. 11:19

 

문자열 매칭

 

s = "오늘은 기분이 '매우' 좋습니다."

# 단순 문자열 확인
print("기분이" in s)		# True
print("나쁩니다" in s)		# False

# 정의된 문자열 리스트 중 일치하는 단어가 있는지 확인
print(any(x in s for x in ["좋습니다", "나쁩니다"])) 		# True
print(any(x in s for x in ["그저그래요", "나쁩니다"])) 		# False


# 정의된 문자열 리스트 모두가 일치하는지 확인
print(all(x in s for x in ["오늘은", "좋습니다"]))		# True
print(all(x in s for x in ["오늘은", "나쁩니다"]))		# False

 


 

리스트 매칭

 

a=["hello", "world", "python"]
b=["hello", "bye", "good"]

# 같은 개체 찾기
y = [x for x in b if x in a]		# ['hello']

# 서로 다른 개체 찾기
y = [x for x in a+b if x not in a or x not in b]	# ['world', 'python', 'bye', 'good']

 


 

정규식(re, Regural Expression)

 

import re

s = "오늘은 기분이 '매우' 좋습니다."

# '매우'를 찾아서 반환
re.findall("'.+?'", s)		# ["'매우'"]

# '매우'가 있는지 확인
re.search("'.+?'", s)		# True

 

Comments