How to check if the typed string is only '0' and '1'?

Asked

Viewed 187 times

2

I want to validate if the typed string represents a binary number, but the way I did is not working very well:

binario = str(input('Binário: '))
if '01' in binario:
    quebrar_string = [c for c in binario]       #Pega a string, divide por digitos, e adiciona a uma lista. ex: 101, divindo, fica: ['1','0','1']
    inteiros = []
    resultado = 0
    for c in quebrar_string:                    #Pega cada digito da string, e converte para inteiro.
        inteiros.append(int(c))
    inverter = inteiros[::-1]                   #Inverte a string pra facilitar os calculoss
    for c in range(0,len(binario)):
        resultado += (2 ** c) * inverter[c]     #Realiza o cálculo citado anteriormente
    print(resultado)                            #Imprime a conversão do binario para decimal
else:
    print('O número digitado não é um binário.')
  • If one of the answers below solved your problem and there was no doubt left, choose the one you liked the most and mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

2 answers

4

Ever heard of regular expressions? The following regular expression can help you.

 import re
 teste = "101010"
 print(re.match("^[10]+$", teste ) != None)

The value you want to test is in the test variable (change and test others). If the result of the comparison is true it is because the number consists only of 1s and 0s.

  • beauty brother, I will check this module better. And thanks again

4

Even though the question is:

How to check if the typed string is only '0' and '1'?

Your code presents other problems and the most obvious is the over-processing to perform simple tasks that are check and convert a entrada which is supposed to represent an integer in binary.

In Python are made available some built-in functions and one of these functions is the int().
That function int() has two parameters ( x , base = 10 ) and has the purpose of converting x in a whole.
When the parameter base this other parameter is informed x, which in that case may be str, bytes or bytearray, is converted into a number whole according to the numerical basis provided by the parameter base and generates an exception of the type ValueError case x is of the right kind but with inappropriate value.

There are several possibilities in Python to perform this verification and subsequent conversion of a presumed numerical representation into binary contained in an integer string.
However knowing this information, the above mentioned, it is possible to use only the function int() to perform the conversion and take advantage of the function’s behavior in generating an exception when fed the inappropriate value.
For this it is possible to perform the nested conversion to a treatment of exceptions which will act as a control mechanism for the conversion result if the conversion is successful or not.

entrada = '110011101'

try:                                            #Inicializa um bloco de tratamento de erros...
    retorno = int(entrada, 2)                   #Atribui a retorno a conversão da entrada na base 2.
except ValueError:                              #Caso haja uma exceção do tipo ValueError...
    retorno = 'Há um algarismo não binário.'    #Atribui a retorno uma frase.

print(retorno)                                  #Imprime 413

It is also possible to perform the same task without resorting to an exception treatment.
In this case it is necessary to perform a check of each of the characters of the entry to know if they are suitable for the operation. To verify that all elements of an eternal meet a certain condition it is possible to use the built-in function all(), that just returns true all the elements of an eternal true, next to a generating expression:

c in '01' for c in entrada

That can be read like this:

For each character c in entrada
Check whether c is contained in the string 01...
- if yes adding an element to the generator true.
- if nay adding an element to the generator false.

Then the function all() will go through all the elements produced with this generating expression and will only return true where all these elements are true else it returns false.

entrada = '11001111111111111111101'

if all(c in '01' for c in entrada):            #Verifica se a entrada é valida...
    retorno = int(entrada, 2)                  #Se a entrada é valida efetua a conversão e atribui a retorno.
else:
    retorno = 'Há um algarismo não binário.'   #Se a entrada não é valida atribui a retorno um texto.

print(retorno)                                 #imprime 6815741

If the base conversion is required to be calculated by exercise it is possible to use the built-in function enumerate() that for each member of an iterable is returns a tuple containing a count (started from 0) and the member itself.

entrada = '11001111111111111111101'

if all(c in '01' for c in entrada):            #Verifica se a entrada é valida...
    retorno = 0
    for c in enumerate(entrada[::-1]):         #Enumere do último ao primeiro cada caractere da entrada...
      retorno += int(c[1]) * (2 ** c[0])       #Converte o caractere de base binária para base decimal.
else:
    retorno = 'Há um algarismo não binário.'   #Se a entrada não é valida atribui a retorno um texto.

print(retorno)                                 #imprime 6815741

Browser other questions tagged

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