Python | Check if a given string is a binary string or not

Counters | Python Methods and Functions | String Variables

Examples :

 Input: str = "01010101010" Output: Yes Input: str = "geeks101" Output: No 

Approach 1 : Using

# Python program to check
# if the string is binary or not

 
# function to check
# line is accepted or not

def check (string):

 

  # install string transform function

< code class = "undefined spaces">  # to the character set.

p = set (string)

 

# declare a set of & # 39; 0 & # 39 ;, & # 39; 1 & # 39 ;.

s = { '0' , '1' }

 

# check that the p set is the same as set s

# or set p contains only & # 39; 0 & # 39;

  # or set p contains only & # 39; 1 & # 39;

  # or not, if there is one condition

# true, then the line was accepted

  # not otherwise.

if s = = p or p = = { '0' } or p = = { ' 1'  }:

print ( "Yes" )

else :

print ( "No" )

 

 

 
# driver code

if __ name__ = = "__ main __" :

 

string = " 101010000111 "

  

# function call

check (string)

Output:

 Yes 

Approach 2: simple

# Python program to check
# if the string is binary or not

 
# function to check
# line was accepted or not

def check2 (string):

 

# initialize variable t

# with the line & # 39; 01 & # 39;

t = '01'

  

# initialize the count variable

  # with a value of 0

  count = 0

  

  # loop through each character

# lines.

for char in string:

 

# check if character is present in

# string t or not.

# if this condition is true

# assign 1 to count variable

  # and break out of the for loop

# otherwise pass

if char not in t:

count = 1

  break

else :

pass

  

# after exiting the loop

# check the counter value is not zero or not

# if the value nonzero, en condition is true

# and the string is not accepted

# otherwise the line is accepted

if count:

print ( "No" )

else :

print ( " Yes " )

  

 

 
# driver code

  if __ name__ = = "__ main__" :

 

string = "001021010001010"

 

  # function call

check2 (string)

Exit :

 No 




Get Solution for free from DataCamp guru