파이썬 문자열이 동일한지 확인하는 방법

파이썬 문자열의 동일성은 == 연산자나 __eq__() 함수를 사용하여 확인할 수 있습니다. 파이썬 문자열은 대소문자를 구분하므로 이러한 동일성 확인 방법도 대소문자를 구분합니다.

파이썬 문자열 동일성

두 문자열이 동일한지 여부를 확인하는 몇 가지 예제를 살펴보겠습니다.

s1 = 'Apple'

s2 = 'Apple'

s3 = 'apple'

# 대소문자 구분 동일성 확인
if s1 == s2:
    print('s1 and s2 are equal.')

if s1.__eq__(s2):
    print('s1 and s2 are equal.')

결과:

s1 and s2 are equal.
s1 and s2 are equal.

만약 부등호를 사용하여 부등성을 확인하려면 != 연산자를 사용할 수 있습니다.

if s1 != s3:
    print('s1 and s3 are not equal')

결과: s1과 s3는 동일하지 않습니다

파이썬 문자열 대소문자 구분 없는 동일성 확인

때로는 두 문자열의 동일성을 확인할 때 대소문자를 고려하지 않는 경우가 있습니다. 이러한 경우에는 대소문자를 고려하지 않는 동일성 확인을 위해 casefold(), lower() 또는 upper() 함수를 사용할 수 있습니다.

if s1.casefold() == s3.casefold():
    print(s1.casefold())
    print(s3.casefold())
    print('s1 and s3 are equal in case-insensitive comparison')

if s1.lower() == s3.lower():
    print(s1.lower())
    print(s3.lower())
    print('s1 and s3 are equal in case-insensitive comparison')

if s1.upper() == s3.upper():
    print(s1.upper())
    print(s3.upper())
    print('s1 and s3 are equal in case-insensitive comparison')

결과:

apple
apple
s1 and s3 are equal in case-insensitive comparison
apple
apple
s1 and s3 are equal in case-insensitive comparison
APPLE
APPLE
s1 and s3 are equal in case-insensitive comparison

파이썬 문자열에 특수 문자가 포함된 경우 동일한지 여부

일부 예제를 살펴보겠습니다. 여기에는 문자열에 특수 문자가 포함된 경우를 보여주는 몇 가지 예제가 포함되어 있습니다.

s1 = '$#ç∂'
s2 = '$#ç∂'

print('s1 == s2?', s1 == s2)
print('s1 != s2?', s1 != s2)
print('s1.lower() == s2.lower()?', s1.lower() == s2.lower())
print('s1.upper() == s2.upper()?', s1.upper() == s2.upper())
print('s1.casefold() == s2.casefold()?', s1.casefold() == s2.casefold())

출력:

s1 == s2? True
s1 != s2? False
s1.lower() == s2.lower()? True
s1.upper() == s2.upper()? True
s1.casefold() == s2.casefold()? True

파이썬에서 두 문자열이 동일한지 여부를 확인하는 방법에 대한 내용은 여기까지입니다.

전체 스크립트 및 더 많은 파이썬 문자열 예제는 저희 GitHub 저장소에서 확인할 수 있습니다.

Source:
https://www.digitalocean.com/community/tutorials/python-string-equals