Go Back

Write a Python Program String to binary python

12/3/2023
All Articles

#Python #Program #String #binary python

Write a Python Program  String to binary python

Write a Python Program String to binary

Here we can convert a string to its binary representation in Python using the bin() function and some additional string manipulation. Here's a simple example:
 

# convert a string to binary
def string_to_binary(input_string):
    binary_result = ''.join(format(ord(char), '08b') for char in input_string)
    return binary_result

# input
text = "hellow Developer Indian"
binary_representation = string_to_binary(text)

print(f'Text: "{text}"')
print(f'Binary Representation: {binary_representation}')
 

Conclusion

Initially, we have defined the string 'hellow Developer Indian' as the binary string that needs to be transformed.
The string we have constructed needs to be pass to function string_to_binary ,which takes each character from the string and converts it to binary.

It is simple to understand with the method , which indicates ours input  and what its binary counterpart is.
Next, we utilised the print() method.

The final step is to display the value of the overall result, which is saved in the variable binary_representation.

Here we can provide you python tutorial to learn it.

Article