We can check if a string is binary in Python by iterating through each character in the string and verifying if it’s either ‘0’ or ‘1’. Here’s a simple function to do that:
def is_binary(s):
for char in s:
if char != '0' and char != '1':
return False
return True
# Example usage:
string1 = "101010101" # binary string
string2 = "10101012" # non-binary string
print(is_binary(string1)) # Output: True
print(is_binary(string2)) # Output: False
This function iterates through each character in the input string s
.
If any character is not ‘0’ or ‘1’, it returns False
, indicating that the string is not binary. If all characters are ‘0’ or ‘1’, it returns True
, indicating that the string is binary.