
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to convert string to binary in Python?
To convert a string to binary, you need to iterate over each character and convert it to binary. Then join these characters together in a single string. You can use format(ord(x), 'b') to format the character x as binary. For example:
>>>st = "hello world" >>>' '.join(format(ord(x), 'b') for x in st) '11010001100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
You can alsomap all characters to bin(number) using bytearray to get the array of allcharacters in binary. For example:
>>>st = "hello world" >>>map(bin,bytearray(st)) ['0b1101000','0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111','0b1101111', '0b1110010', '0b1101100', '0b1100100']
- Related Articles
- How to Convert Decimal to Binary Using Recursion in Python?
- Java Program to convert int to binary string
- C# program to convert binary string to Integer
- How to convert list to string in Python?
- How to convert int to string in Python?
- Python program to convert floating to binary
- How to convert a string to dictionary in Python?
- How to convert string to JSON using Python?
- Convert decimal to binary number in Python program
- How to Convert Binary to Decimal?
- How to Convert Decimal to Binary?
- How to Convert Binary to Octal?
- How to Convert Binary to Hexadecimal?
- Python program to convert decimal to binary number
- Python Program to Convert Gray Code to Binary

Advertisements