logo

Python에서 문자열에 문자가 있는지 확인

모든 프로그래밍 언어에서 가장 자주 수행되는 작업 중 하나는 주어진 문자열에 하위 문자열이 포함되어 있는지 확인하는 것입니다. Python에는 주어진 문자열에 문자가 포함되어 있는지 확인하는 다양한 방법이 있습니다. 비교 연산 도구 역할을 하는 Python의 'in' 연산자는 Python 문자열에 문자가 포함되어 있는지 확인하는 가장 빠르고 쉬운 방법입니다. 문자열에 하위 문자열이 포함되어 있는지 확인하는 것도 find(), index(), count() 등과 같은 다른 Python 함수를 사용하면 도움이 됩니다.

Python의 'in' 연산자 사용

Python의 'in' 연산자는 문자열이 하위 문자열로 구성되어 있는지 여부를 확인하는 가장 빠르고 쉬운 방법입니다. 문자열에 해당 문자가 있으면 이 작업은 부울 true를 반환합니다. 그렇지 않으면 false를 반환합니다.

암호

 # Python program to show how to use the in operator to check if a string contains a substring # Creating a string str='Python Tutorial' print('The string 'tut' is present in the string: ', 'Tut' in str) 

산출:

 The string 'tut' is present in the string: True 

왼쪽 인수로 주어진 문자열이 오른쪽 인수로 주어진 문자열 안에 포함되면 'in' 연산자는 True를 반환합니다. 각 측면에 하나씩 두 개의 매개변수를 허용합니다. Python의 'in' 연산자는 대소문자를 구분하는 연산자이므로 대문자와 소문자를 별도로 처리합니다.

__contains__() 함수 사용

Python의 String 클래스의 __contains__() 함수는 주어진 문자열에 하위 문자열이 포함되어 있는지 여부를 확인하는 방법도 제공합니다. Python의 'in' 작업은 암시적으로 사용될 때 __contains__() 메서드를 호출합니다. 클래스 객체가 'in' 및 'not in' 연산자의 오른쪽에 나타나면 동작은 __contains__ 메서드에 의해 정의됩니다. 가능하더라도 이 방법을 명시적으로 사용하지 않기로 결정했습니다. 첫 번째 문자로 밑줄이 있는 함수는 의미상 비공개로 간주되지만 가독성을 위해 'in' 연산자를 사용하는 것이 좋습니다.

암호

 # Python program to show how to use the __contain__ method to check if a string contains a substring # Creating a string string = 'Python Tutorial' print('The string 'tut' is present in the string: ', string.__contains__('Tut')) 

산출:

 The string 'tut' is present in the string: True 

Python의 str.find() 메서드 사용

string.find() 기술을 사용할 수도 있습니다. find() 함수는 주어진 문자열에 하위 문자열이 존재하는지 확인합니다. 찾으면 find() 함수는 -1을 반환합니다. 그렇지 않으면 문자열 내부의 하위 문자열의 시작 인덱스를 제공합니다.

암호

 # Python program to find a character in a string and get its index # Creating a string string = 'Python Tutorial' index = string.find('T') if index != -1: print('The character 'T' is present in the string at: ', index) else: print('The character is not present in the string') 

산출:

 The character 'T' is present in the string at: 7 

이 접근 방식은 허용됩니다. 그러나 str.find()를 사용하는 것은 이 작업을 완료하는 데 있어 덜 Python적인 방법입니다. 비록 더 길고 다소 뒤죽박죽되어 있지만 여전히 작업을 수행합니다.

str.count() 메소드 사용

문자열 내의 특정 하위 문자열의 인스턴스 수를 계산하려면 Python count() 함수를 사용하십시오. 함수는 주어진 문자열에서 부분 문자열이나 문자를 찾을 수 없으면 0을 제공합니다.

암호

 # Python program to check a character is present in the string using the count() function # Creating a string string = 'Python Tutorial' count = string.count('o') if count != 0: print(f'The character 'o' is present in the string {count} times.') else: print('The character is not present in the string') 

산출:

 The character 'o' is present in the string 2 times.