How to convert text to binary code in Python

1 Answer

0 votes
def text2bin(txt):
    bin_result = ""

    for char in txt:
        # Convert character to ASCII and then to binary
        binary = bin(ord(char))[2:]  # Remove the '0b' prefix
        # Pad binary to ensure it is 8 bits long
        binary = binary.zfill(8)
        # Append to the result with a space
        bin_result += binary + " "

    return bin_result.strip()  # Remove trailing space

print(text2bin("Python"))



'''
run:

01010000 01111001 01110100 01101000 01101111 01101110

'''

 



answered Apr 13 by avibootz
...