파이썬에서 두개의 문자열 비교하는 다양한 방법들을 소개합니다.
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 str3
2. 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 str3
3. 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 str1
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 str1
5. 정규표현식으로 문자열 패턴 비교
다음과 같이 정규표현식의 패턴과 일치하는지 비교할 수도 있습니다. 아래 예제는 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 소수점 반올림, round() 예제
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- 파이썬 주석 처리, 단축키 소개
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - 딕셔너리 정리 및 예제
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 반복문으로 리스트 순회 방법 (+ Index 출력)
- Python - with로 파일 열고 닫기