Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python – 문자 목록의 테스트 문자열 및 그 반대

<시간/>

문자열을 문자 목록에서 테스트해야 하거나 그 반대의 경우에도 간단한 'in' 연산자와 'join' 메서드를 사용합니다.

아래는 동일한 데모입니다 -

예시

my_string = 'python'

print("The string is :")
print(my_string)

my_key = ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't']
print("The key is ")
print(my_key)
joined_list = ''.join(my_key)

my_result = my_string in joined_list

print("The result is :")
if(my_result == True):
   print("The string is present in the character list")
else:
   print("The string is not present in the character list")

출력

The string is :
python
The key is
['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't']
The result is :
The string is present in the character list

설명

  • 문자열이 정의되어 콘솔에 표시됩니다.

  • 키 값이 정의되어 콘솔에 표시됩니다.

  • .join() 함수를 사용하여 키의 요소를 결합하여 문자열을 만듭니다.

  • 이것은 변수에 할당됩니다.

  • 문자열과 키를 비교하여 위에서 언급한 목록에 문자열이 있는지 확인합니다.

  • 이 결과는 변수에 할당됩니다.

  • 이 결과의 Boolean 값에 따라 콘솔에 해당 메시지가 표시됩니다.