×

Convert String to Binary in Python

String to binary

The strings can be defined as the array of Unicode code characters.

Binary

Binary is defined as the number system which consists two symbols 0 and 101. It is base-2 numeral system. The computers perform operations in binary.

The computer views the string in binary format and the binary number is an ASCCI value of string which is converted.  

Method 1: Using ord() function

Firstly, we add the individual ASCII values of the string to a list with the use of ord() function.

The ord function helps in converting the character and gives the string's ASCII value.

Example:

# string initialization  

test_str = "JavaTpoint"

# original string 

print("The original string is : " + str(test_str))

# String to binary conversion

res = ''.join(format(ord(i), 'b') for i in test_str)

# result 

print("The string after binary conversion : " + str(res))

Output:

The original string is : JavaTpoint

The string after binary conversion : 1001010110000111101101100001101010011100001101111110100111011101110100

Method 2: Using bytearray

The bytearray function is used for conversion of string. All characters are mapped into bin using bytearray and it returns the character's array in binary.

Example:

test_str = "JavaTpoint"

# original string 

print("The original string is : " + str(test_str))

# String to binary converting

res = ''.join(format(i, 'b') for i in bytearray(test_str, encoding ='utf-8'))

# result 

print("The string after binary conversion : " + str(res))

Output:

The original string is : JavaTpoint

The string after binary conversion : 1001010110000111101101100001101010011100001101111110100111011101110100

Method 3: Using map() function

By using bytearray, all character can also be mapped into Bin. The function bin() is used for converting decimal number into binary number.

Example:

st = "JavaTpoint"

# original string 

print("The original string is : " + str(st))

result = ' '.join(map(bin, bytearray(st, "utf-8")))

# result 

print("The string after binary conversion : " + str(result))print("The string after binary conversion : " + str(res))

Output:

The original string is : JavaTpoint

The string after binary conversion : 0b1001010 0b1100001 0b1110110 0b1100001 0b1010100 0b1110000 0b1101111 0b1101001 0b1101110 0b1110100

Related Topics

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

__GETITEM__ and __SETITEM__ in Python

These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like...

3 minutes read.

Enumerate() Function in Python

The enumerate() function in Python is used to convert a data collection object into an enumerate object. It returns an object that contains a counter as a key for each...

3 minutes read.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Python tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Python String splitlines() method

Python String splitlines() method The string.splitlines() method in Python splits the specified string and returns a list of the lines in the string, breaking at line boundaries.  Syntax splitlines([keepends]) Parameter keepends(optional): This parameter specifies if...

1 minute read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.