Python: conditions for various symbols

Asked

Viewed 329 times

1

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

  • You need to check if all the symbols are in the word?

  • I need him to check simbolos, has some within the word.

2 answers

3


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

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')
  • Exactly, it was worth the force

1

I made a simple example, you cannot compare an entire list to a string, so to make it easier I used lambda function that will go through the list of symbols and check one by one if the special string is in the phrase.

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

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

Also note that I have changed ' '' to ' ', as this is how python recognizes " as string. The code output will be:

Output: True
  • It’s a good solution, but in my case I’m using to remove some blanks and I split the sentence to pick up the words.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.