Python: conditions for various symbols

1

I have a doubt, I remember already having seen the resolution somewhere, but I'm not finding it anymore. So the problem has several symbols for example simbolos = ('!','?',',','\'') here it is like tuple which is how i imagined that employee, but no. I want to check all of them in a if like this: if (simbolos in palavra): .

    
asked by anonymous 29.05.2018 / 02:31

2 answers

3

If you need to check if at least one operator is in the word, you can use the any function:

if any(simbolo in palavra for simbolo in simbolos):
    print('Pelo menos um símbolo está na palavra')

Or you can use sets and check for intersection:

simbolos = set(('!', '?', ',', '\''))
palavra = set('Pergunta?')

if simbolos & palavra:
    print('Pelo menos um símbolo está na palavra')
    
29.05.2018 / 02:54
1

I made a simple example, you can not compare a whole list with a string, so to facilitate I used lambda function that will go through the list of symbols and check one by one if the special string is in the sentence.

simb = ['!','?',',','\']
frase = 'Somente hoje, eu cheguei mais cedo!'

if lambda x: simb in frase:
    print True
else:
    print False

Notice also that I've changed the '\' 'to' \ ', because this is how python recognizes the \' string '. The output of the code will be:

Output: True
    
29.05.2018 / 03:03