How to scan a string for specific characters in Python?

PythonServer Side ProgrammingProgramming

If you want to check if a given character exists in a string, you can use in. For example,

>>> s = "Hello world"
>>> 'e' in s
True

If you have a list of characters you want to search, you can use Sets. Add these character in the set and use the any function to check if any of these characters exist in the string. For example,

from sets import Set
chars = Set('0123456789$,')
s = "I have 9 cats"
if any((c in chars) for c in s):
    print('Found')
else:
    print('Not Found')

This will give the output:

Found

If you want to check if all of these characters exist in the string, just replace any with all. For example,

from sets import Set
chars = Set('0123456789$,')
s = "I have 9 cats"
if all((c in chars) for c in s):
    print('Found')
else:
    print('Not Found')

This will give the output:

Not Found
raja
Published on 14-Dec-2017 08:02:47
Advertisements