파이썬에서 두개의 문자열 비교하는 다양한 방법들을 소개합니다.
1. '==', '!=' 키워드로 문자열이 같은지, 다른지 확인
==, !=으로 두개의 문자열이 서로 같은지 다른지 비교할 수 있습니다.
str1 = "Hello, World"
str2 = "Hello, World"
str3 = "Hello, Python"
if str1 == str2:
print("str1 is equal to str2")
if str1 != str3:
print("str1 is not equal to str3")Output:
str1 is equal to str2
str1 is not equal to str32. 'in', 'not in' 키워드로 문자열 포함 여부 확인
in, not in으로 문자열에 특정 문자열이 포함되어있는지, 포함안되어있는지 확인할 수 있습니다. (Java의 contains()와 비슷합니다.)
str1 = "Hello"
str2 = "Hello, World"
str3 = "Python"
if str1 in str2:
print("str2 contains str1")
if str3 not in str2:
print("str2 doesn't contains str3")Output:
str2 contains str1
str2 doesn't contains str33. startswith()로 특정 문자열로 시작하는지 확인
문자열이 startswith()의 인자로 전달된 문자열로 시작하는지 확인할 수 있습니다. 부정은 if not str2.startswith()처럼 앞에 not을 붙이면 됩니다.
str1 = "Hello"
str2 = "Hello, World"
if str2.startswith(str1):
print("str2 starts with str1")Output:
str2 starts with str1startswith() 함수에 대한 자세한 내용은 "Python - String startswith(), 어떤 문자열로 시작하는지 확인"를 참고해주세요.
4. endswith()로 특정 문자열로 끝나는지 확인
문자열이 endswith()의 인자로 전달된 문자열로 끝나는지 확인할 수 있습니다. 부정은 if not str2.startswith()처럼 앞에 not을 붙이면 됩니다.
str1 = "World"
str2 = "Hello, World"
if str2.endswith(str1):
print("str2 ends with str1")Output:
str2 ends with str15. 정규표현식으로 문자열 패턴 비교
다음과 같이 정규표현식의 패턴과 일치하는지 비교할 수도 있습니다. 아래 예제는 Hello로 시작하고 World로 끝나는 패턴의 문자열을 찾습니다. re.match(pattern, str)는 문자열이 패턴과 일치하면 True를 리턴합니다.
import re
def check_pattern(str):
if re.match("Hello.*World", str):
print("Pass")
else:
print("Fail")
str1 = "Hello, World"
str2 = "Hello----World"
str3 = "Hello~~~~~World"
check_pattern(str1)
check_pattern(str2)
check_pattern(str3)Output:
Pass
Pass
Pass정규표현식에 대한 자세한 내용은 Python - Regex를 참고해주세요.
Loading script...
Related Posts
- Python - Yaml 파일 파싱하는 방법
- Python - 파일 내용 삭제
- Python - for문에서 리스트 순회 중 요소 값 제거
- Python - 두 리스트에서 공통 요소 값 찾기
- Python - 문자열 앞(뒤)에 0으로 채우기
- Python - 공백으로 문자열 분리
- Python - 중첩 리스트 평탄화(1차원 리스트 변환)
- Python - 16진수 문자열을 Int로 변환
- Python - 두 날짜, 시간 비교
- Python f-string으로 변수 이름, 값 쉽게 출력 (변수명 = )
- Python - nonlocal과 global 사용 방법
- Python 바다코끼리 연산자 := 알아보기
- Python - pip와 requirements.txt로 패키지 관리
- Python - 딕셔너리 보기 좋게 출력 (pprint)
- Python - Requests 사용 방법 (GET/POST/PUT/PATCH/DELETE)
- Python - 온라인 컴파일러 사이트 추천
- Python - os.walk()를 사용하여 디렉토리, 파일 탐색
- Python - 문자열 비교 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트의 첫번째 요소 제거
- Python - 리스트의 마지막 요소 제거
- Python 소수점 버림, 4가지 방법
- Python 코드 안에서 버전 확인 방법
- Python 소수점 반올림, round() 예제
- Python - 리스트 평균 구하기, 3가지 방법
- Python - bytes를 String으로 변환하는 방법
- Python - String을 bytes로 변환하는 방법
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - 람다(Lambda) 함수 사용 방법
- Python - dict 정렬 (Key, Value로 sorting)
- Python - range() 사용 방법 및 예제
- Python - 리스트를 문자열로 변환
- Python - 문자를 숫자로 변환 (String to Integer, Float)