웹사이트 검색

Python 목록에서 문자열 찾기


Python in 연산자를 사용하여 목록에 문자열이 있는지 여부를 확인할 수 있습니다. 문자열이 목록에 없는지 확인하는 not in 연산자도 있습니다.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']

# string in the list
if 'A' in l1:
    print('A is present in the list')

# string not in the list
if 'X' not in l1:
    print('X is not present in the list')

산출:

A is present in the list
X is not present in the list

권장 자료: Python f-strings 목록에서 확인할 문자열을 사용자에게 입력하도록 요청하는 또 다른 예를 살펴보겠습니다.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = input('Please enter a character A-Z:\n')

if s in l1:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')

산출:

Please enter a character A-Z:
A
A is present in the list

Python count()를 사용하여 목록에서 문자열 찾기

count() 함수를 사용하여 목록에서 문자열의 발생 횟수를 얻을 수도 있습니다. 출력이 0이면 목록에 문자열이 없음을 의미합니다.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = 'A'

count = l1.count(s)
if count > 0:
    print(f'{s} is present in the list for {count} times.')

목록에서 문자열의 모든 인덱스 찾기

목록에 있는 문자열의 모든 색인 목록을 가져오는 내장 함수는 없습니다. 다음은 문자열이 목록에 있는 모든 인덱스 목록을 가져오는 간단한 프로그램입니다.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = 'A'
matched_indexes = []
i = 0
length = len(l1)

while i < length:
    if s == l1[i]:
        matched_indexes.append(i)
    i += 1

print(f'{s} is present in {l1} at indexes {matched_indexes}')

출력: A는 [A, B, C, D, A, A, C]의 인덱스 [0, 4, 5]에 있습니다.

GitHub 리포지토리에서 전체 Python 스크립트와 더 많은 Python 예제를 확인할 수 있습니다.