Error searching string inside another python string

Asked

Viewed 85 times

1

I’m running some tests and the code seems to be correct logically, but when I use an example, "what day is it today?" as self.phrase it only returns me the first if (of the hours), if I put as self.phrase = "What day of the week is today?" the same mistake happens, where I’m missing?

def about_time(self):
    temp_atual = datetime.datetime.now()
    if 'são' or 'sao' in self.frase:
        print("Agora são " + str(temp_atual.hour) + " horas, " + str(temp_atual.minute) + " minutos e " + str(temp_atual.second) + " segundos.")
    elif 'dia' and 'hoje' in self.frase:
        print("Hoje é dia " + str(temp_atual.day) + "/" + str(temp_atual.month) + "/" + str(temp_atual.year))
    elif 'dia da semana' in self.frase:
        dia = temp_atual.isoweekday()
        if dia == 1:
            dia = "segunda-feira"
        if dia == 2:
            dia = "terça-feira"
        if dia == 3:
            dia = "quarta-feira"
        if dia == 4:
            dia = "quinta-feira"
        if dia == 5:
            dia = "sexta-feira"
        if dia == 6:
            dia = "sábado"
        if dia == 7:
            dia = "domingo"
        print("Hoje é " + dia)
  • 2

    This is wrong 'são' or 'sao' in self.frase, would have to be 'são' in self.frase or 'sao' in self.frase... this too is wrong 'dia' and 'hoje' in self.frase:, should be 'dia' in self.frase and 'hoje' in self.frase:

  • can’t I pass two parameters of a made in the case of "in self.frase"? I thought I could, so it would be simpler. But thank you!

  • That’s not the point, the point is that OR and AND are logical operators, they don’t work within in, what this between them are separate things, ie before the OR is a check, after the OR is another check, the same goes for AND, only it changes only the behavior, but still the logical operations are separated.

3 answers

3


Your ifs are incorrect, and and or are logical operators, they are not part of the in, so this is wrong:

if 'são' or 'sao' in self.frase

Should be:

if 'são' in self.frase or 'sao' in self.frase

This too is wrong

if 'dia' and 'hoje' in self.frase:

should be

if 'dia' in self.frase and 'hoje' in self.frase:

Each or or and separate instructions for logical operations, meaning they do not work within the in, but yes "backwards", so the use is this:

if <instrução> or <outra instrução>:

In each of these instructions you can use ==, !=, is, is not, but they are instructions to the part, so in its first if It’s like I’m doing this:

if ('são') or ('sao' in self.frase)

Checks first if 'são' if you failed to check 'sao' in self.frase, as 'são' always passes in the if, then even if the phrase was different it would come in anyway, because 'são' was not being compared to anything.

2

I gave a little refactoring in your code:

def about_time(self):
    temp_atual = datetime.datetime.now()
    if any(_ in self.frase for _ in ('sao', 'são')):
        print(temp_atual.strftime("Agora são %H horas, %M minutos e %S segundos."))
    elif 'dia' in self.frase:
      if 'hoje' in self.frase:
        print(temp_atual.strftime("Hoje é dia %d/%m/%Y"))
      elif 'semana' in self.frase:
        dia = [None, 'segunda-feira', 'terça-feira',
        'quarta-feira', 'quinta-feira', 'sexta-feira',
        'sábado', 'domingo'][temp_atual.isoweekday()]
        print("Hoje é " + dia)

Since isoweekday() returns a value between 1 and 7, put a None in the list at index 0, but, could be anything... Then we access the list of days by the index (1 to 7, remember?), which could also be written as a dictionary:

dia = {i: dia for i, dia in enumerate(['segunda-feira', 'terça-feira',
                                       'quarta-feira', 'quinta-feira', 
                                       'sexta-feira', 'sábado', 'domingo'], start=1)}.get(temp_atual.isoweekday())

any one of these forms saves us from that giant block of ifs/elifs.

I also recommend a look at the method strftime() of the object datetime, makes it easier to handle strings and dates.

Edit: Adding the Function Explanation any() at the request of the PO

The function any() receives an eternal and returns True if any element of that eternal being equivalent to True, in the case:

(_ in self.frase for _ in ('sao', 'são'))
# é parecido a:
compares = []
for palavra in ('sao', 'são'):
  if palavra == self.frase:
    compares.append(True)
  else:
    compares.append(False)

the eternal would be a generator of 2 elements ('sao', 'são') compared against self.frase, if we consider self.frase = 'teste' the generator would look like: (False, False) since none of the two words is equal to self.frase, and how none of the elements is equal to True, we do not enter the if.

There is also a similar function, all(), the difference being that all() only returns True if all elements were equivalents to True.

  • Can you explain that line better: if any(_ in self.frase for _ in ('sao', 'são')):? Thanks for the reply, I liked the optimization.

  • If it’s not clear, let me know I rewrite.

-2

    import datetime

def about_time(message):
    temp_atual = datetime.datetime.now()
    if 'são' or 'sao' in message:
        print("Agora são " + str(temp_atual.hour) + " horas, " + str(temp_atual.minute) + " minutos e " + str(temp_atual.second) + " segundos.")
        if 'dia' and 'hoje' in message:
            print("Hoje é dia " + str(temp_atual.day) + "/" + str(temp_atual.month) + "/" + str(temp_atual.year))
            if 'dia da semana' in message:
                dia = temp_atual.isoweekday()
                if dia == 1:
                    dia = "segunda-feira"
                if dia == 2:
                    dia = "terça-feira"
                if dia == 3:
                    dia = "quarta-feira"
                if dia == 4:
                    dia = "quinta-feira"
                if dia == 5:
                    dia = "sexta-feira"
                if dia == 6:
                    dia = "sábado"
                if dia == 7:
                    dia = "domingo"
                print("Hoje é " + dia)
about_time('Que dia é hoje?')

OUTPUT:

Agora são 0 horas, 18 minutos e 45 segundos.
Hoje é dia 9/7/2018
  • 1

    If this is a solution to the question problem, could you describe in words what you have done? A code that may be trivial to you may not be trivial to other users.

Browser other questions tagged

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