0

How do we find a letter or special character present in list of strings? I have a list and want to check if it contains particular letter in it. I tried to do but getting an error.

code:

lst = ['Mangos*','apples,'REd']
for l in lst:
    if l.contains('M') or l.contains('*'):
             print(l)

getting an error:

AttributeError: 'list' object has no attribute 'contains'

Should we not use contains? or what should we to find if a string has particular letter or special character?

Rapooram
  • 49
  • 1
  • 5
  • 1
    Instead of `l.contains('M')` why not use `'M' in l`? – Random Davis Mar 19 '21 at 15:04
  • 2
    Does this answer your question? [Does Python have a string 'contains' substring method?](https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – Random Davis Mar 19 '21 at 15:05

2 Answers2

1
lst = ['Mangos*','apples','REd']
for l in lst:
    if 'M' in l or '*' in l:
             print(l)
Syed Ashraf
  • 102
  • 1
  • 7
1

If you want to find a specific letter in your string you can use a regular expression. first, you need to import os and import re. Then we can create a loop for each match.

import os  
import re 

lst = ['Mangos*','apples','REd']

for l in lst:  
    find = re.findall("M",l)  
    if find:  
        print(l) 

Output

Mangos*