How to check if a string is inside a string set?

Asked

Viewed 536 times

4

In the code below I have the set of strings ('M', 'F') and soon after I ask the user to enter their gender so that the value is recorded.

valores = ('M','F')
print(valores)

sexo = str(input('Digite o seu sexo [M/F]: ')).upper()[0].strip()
print(sexo)

if sexo == valores:
    print('Valor registrado com sucesso.')
else:
    print('Dados incorretos. Digite novamente.')

I want to check if the user’s answer is within the values I set, but I can’t do it because even if I type the correct value, it says it’s wrong. See below:

('M','F')
Digite o seu sexo [M/F]: m
M
Dados incorretos. Digite novamente.

Why is this happening? How can I check whether the value is valid or not ?

  • I can’t detect my mistake

  • 1

    Only one detail: in Python 3, input already returns a string, no need to do str(input(...)). And if you already get her first character (with [0]), also need not call strip after (if the first character is a space, either remove it or not, since you will check if it is M or F and it will not make a difference)

1 answer

4


I didn’t quite understand the "use string as value" part, but rather it is possible to check whether a string is inside a list, tuple and other iterable.

In your example code, the comparison returned False because a string is different of a tuple containing strings, as well as "1" is different from 1. To check if a string is inside an iterable (in your case a string tuple), you must replace the operator == for in. See how it would look:

valores = ('M', 'F')
print(valores)

sexo = input('Digite o seu sexo [M/F]: ').upper()[0].strip()
print(sexo)

if sexo in valores:
    print('Valor registado com sucesso.')
else:
    print('Dados incorretos. Digite novamente.')

The operator in unlike ==, checks whether an object (can be an object of any type) is inside an eternal, or rather, it checks whether the target object contains the object you are specifying.

You can do this check not only with strings, but also with objects of other types. See the examples below:

"Masculino"  in  ["Masculino", "Feminino"]          # True
17           in  [19, 23, 3, 1023, 17, 65]          # True
3            in  ["3", 2, True, "bola"]             # False ("3" é diferente de 3)
True         in  [False, True, False, False]        # True

Remember I told you in checks if an object contains an element ? Then... this verification occurs through the method __contains__ that takes a value and checks whether or not the object is passed. Example:

class MinhaClasse():
    def __contains__(self, value):

        if value == 7:
            return True
        else:
            return False

objeto = MinhaClasse()

3 in objeto  # False
7 in objeto  # True

Note that the object to be checked is always before the operator. So if I reversed the code to objeto in 7, I’d be checking if the object is in the number 7 and besides not working, would still generate an error, because int does not have the method __contains__.

  • I was going to answer, but I saw your answer! I think this is what Ruben wanted! Congratulations

  • Thank you very much!!! That’s exactly what I intended.

  • So I don’t need to put ' ' when I assign a value?

  • a = (text1, text2), if I want to check if there is a string text in a variable, I use the function IN, if number is used ==

  • It is necessary to put the quotes, because a tuple is a set of elements (in your case a set of strings). And as you may know, to create a string, it is necessary to use quotation marks.

  • Thanks for the help! Excuse my ignorance, but I’m starting to take the first steps in programming and I’m trying to learn by youtube and websites

  • Don’t worry, we all start from scratch. The last part of the answer is a little more "advanced" so ignore it for now until you start studying Object-Oriented Programming.

  • ;) thanks, it will be useful for sure. For now I am in the if, loop and while conditions. But this doubt arose during an exercise. He never took on the masculine nor the feminine and so the loop did not stop as it was intended. I’ve had three hours to try to solve this problem that you solved in a second

Show 3 more comments

Browser other questions tagged

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