Podemos usar o operador Python in
para verificar se uma string está presente na lista ou não. Também há um operador not in
para verificar se uma string não está presente na lista.
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
# string na lista
if 'A' in l1:
print('A is present in the list')
# string não está na lista
if 'X' not in l1:
print('X is not present in the list')
Output:
A is present in the list
X is not present in the list
Leitura recomendada: f-strings Python Vamos ver outro exemplo onde pediremos ao usuário para inserir a string a ser verificada na lista.
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')
Output:
Please enter a character A-Z:
A
A is present in the list
Python Encontrar String na Lista usando count()
Também podemos usar a função count() para obter o número de ocorrências de uma string na lista. Se a saída for 0, significa que a string não está presente na lista.
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.')
Encontrando todos os índices de uma string na lista
Não há uma função integrada para obter a lista de todos os índices de uma string na lista. Aqui está um programa simples para obter a lista de todos os índices onde a string está presente na lista.
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}')
Output: A está presente em ['A', 'B', 'C', 'D', 'A', 'A', 'C'] nos índices [0, 4, 5]
Você pode conferir o script Python completo e mais exemplos em Python no nosso Repositório do GitHub.
Source:
https://www.digitalocean.com/community/tutorials/python-find-string-in-list