Python의 in
연산자를 사용하여 문자열이 목록에 있는지 확인할 수 있습니다. 또한 not in
연산자도 있어 목록에 문자열이 없는지 확인할 수 있습니다.
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
# 목록 내의 문자열
if 'A' in l1:
print('A is present 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
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 is present in ['A', 'B', 'C', 'D', 'A', 'A', 'C'] at indexes [0, 4, 5]
당사의 GitHub 저장소에서 완전한 파이썬 스크립트 및 더 많은 파이썬 예제를 확인할 수 있습니다.
Source:
https://www.digitalocean.com/community/tutorials/python-find-string-in-list