- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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']
Advertisements