Cast to byte python

How to Convert Python string to byte array with Examples

In this python tutorial, you will learn about python string to byte array. Also, we will check:

  • Python string to byte array encoding
  • Python string to byte array UTF-8
  • Python string to byte array UTF-16
  • Python string to byte array hex
  • Python base64 string to byte array
  • Python binary string to byte array
  • Python JSON string to byte array
  • Python string to a byte array without b
  • Python hex string to byte array
  • Python string to byte array ASCII
  • Python 2.7 string to byte type

Python string to byte array

Now, we can see how to convert string to byte array in python.

  • In this example, I have taken string as “python guides” and to convert that string to byte, I have used new_string = bytes(string,”ascii”).
  • The bytearray() method returns a byte array object.
string = "python guides" new_string = bytes(string,"ascii") print(new_string)

To print the byte, I have used print(new_string). You can see in the output a converted string in the below screenshot.

Читайте также:  What is apache cgi in php

Python string to byte array

Python string to byte array encoding

Here, we can see how to convert string to byte array by encoding in python.

In this example, I have taken a string as”python guides” and encoded it into a byte array by using new_string = string.encode(). The encode() method is used to encode the string.

string = "python guides" new_string = string.encode() print(new_string)

To print the encoded string, I have used print(new_string). You can refer to the below screenshot for the output.

Python string to byte array encoding

Python string to byte array UTF-8

Now, we can see how to convert a string to byte array utf-8 in python

In this example, I have taken a string as “Python guides”. To convert the string into UTF-8, I have used newstring = bytes(string, ‘utf-8’). The bytearray() method returns the byte array object.

string = "Python guides." newstring = bytes(string, 'utf-8') print(newstring)

To print the converted string, I have used print(newstring). Below screenshot shows the output.

Python string to byte array UTF

Python string to byte array UTF-16

Here, we can see how to convert string to byte array UTF-16 in python

  • In this example, I have taken a string as “Python guides”. To convert the string into UTF-16. I have used newstring = bytes(string, ‘utf-16’). The bytearray() method returns the byte array object.
string = "Python guides." newstring = bytes(string, 'utf-16') print(newstring)

To print the converted string, I have used print(newstring). You can see the utf-16 formatted string as the output in the below screenshot.

Python string to byte array UTF-16

Python string to byte array hex

Let’s see how to convert string to byte array hex in python

  • In this example, I have taken a string as string = “AB CD EF” to convert string to byte array hex, I have used newstring = bytearray.fromhex(string).
  • The bytearray.fromhex() this method returns a required string containing hex numbers.
string = "AB CD EF" newstring = bytearray.fromhex(string) print(newstring)

To print the string to byte array hex, I have used print(newstring). You can refer to the below screenshot for the output.

Python string to byte array hex

  • How to create a string in Python
  • How to split a string using regex in python
  • How to concatenate strings in python
  • How to convert an integer to string in python
  • Python convert list to string

Python base64 string to byte array

Here, we can see how to convert base64 string to byte array in python

  • In this example, I have imported a module called base64. This module is used to convert binary data to ASCII characters.
  • To decode the string, we have to use string = base64.b64decode(“Pythonguides”).
import base64 string = base64.b64decode("Pythonguides") print(string)

To print the encoded string, we have to use print(string). You can refer to the below screenshot for the output.

Python base64 string to byte array

Python binary string to byte array

Now, we can how to convert binary string to byte array in python

  • In this example, I have taken a binary string as string = “11000010110001001100011”. To convert the binary string to a byte array.
  • I have used new_string = bytearray(string, “ascii”). The bytearray() method returns the byte array object.
string = "11000010110001001100011" new_string = bytearray(string,"ascii") print(new_string)

To print the converted string, I have used print(new_string). Below screenshot shows the output.

Python binary string to byte array

Python JSON string to byte array

Here, we can see how to convert JSON string to byte array in python

  • In this example, I have imported a module called JSON. The JSON module provides the API which is similar to pickle for converting in the memory.
  • The JSON string is similar to javascript objects. In JSON keys must be a string with a double-quote(” “).
  • json_string = ‘’ is the JSON string.
  • The bytearray() method is used to convert the JSON string to bytearray string, The bytearray() method returns the byte array objects.
import json json_string = '' new_string = bytearray(json_string,"ansi") print(new_string)

To print the converted string, I have used print(new_string). In the below screenshot you can see the output as json string converted into bytearray.

Python JSON string to byte array

Python string to a byte array without b

Here, we can how to convert string to a byte array without b in python

In this example, I have taken a string as b’ python guides’ which includes a byte array, then the string is decoded to print the byte array without b. To decode the string, I have used newstring = string.decode().

string = b'python guides' print(string) newstring = string.decode() print(newstring) 

To print the string without b I have used print(newstring). You can refer to the below screenshot for the output.

Python string to a byte array without b

Python hex string to byte array

Now, we can see how to convert hex string to byte array in python

In this example, I have taken a hex_string = “1A” and to convert that string to bytearray I have used newstring = bytearray.fromhex(hexa_string). The bytearray.fromhex() method returns a required string containing hex numbers.

hexa_string = "1A" newstring = bytearray.fromhex(hexa_string) print(newstring)

To print the hex string converted to a byte array, I have used print(newstring). You can refer to the below screenshot for the output.

Python string to byte array ASCII

Here, we can see how to convert string to bytearray ASCII in python

In this example, I have taken a string as (‘python guides’), To convert the string into bytearray ASCII, I have used string = bytes(str(‘Python guides’).encode(“ascii”)).

string = bytes(str('Python guides').encode("ascii")) print(string)

To print the converted string, I have used print(string). You can refer to the below screenshot for the output

Python string to byte array ASCII

Python 2.7 string to byte type

Here, we can see that a given string is of which type in python

In this example, I have taken three arguments a = “hi”, b=bytes(0), c=25 and to get the type of given string, I have used the type() function. The type() function returns the class type of the argument passed as a parameter.

a="hi" print(type (a)) b=bytes(0) print(type (b)) c=25 print(type (c))

To get the output, I have used print(type (a)) to get the class type of the first argument, and for the second argument. I have used print(type (b)), for the third argument I have used print(type(c)). You can refer to the below screenshot for the output.

Python string to byte type

You may like the following Python tutorials:

  • Python pass by reference or value with examples
  • Python select from a list + Examples
  • Python Tkinter Listbox – How to Use
  • Python copy file (Examples)
  • Python File methods (With Useful Examples)
  • How to convert a String to DateTime in Python
  • How to convert Python degrees to radians
  • Python convert tuple to list
  • Python convert list to string
  • Python shape of an array
  • How to convert dictionary to JSON in Python

In this Python tutorial, we have learned about the Python string to a byte array. Also, We covered these below topics:

  • How to convert string to byte array encoding in Python
  • Python string to byte array UTF-8
  • Python string to byte array UTF-16
  • Python string to byte array hex
  • Python base64 string to byte array
  • Python binary string to byte array
  • Python JSON string to byte array
  • Python string to a byte array without b
  • Python hex string to byte array
  • Python string to byte array ASCII
  • Python 2.7 string to byte type

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

How to convert Python string to bytes?

In this tutorial, we look at how to convert Python string to bytes. We look at all the various methods along with their limitations and caveats.

Table of Contents — Python String to Byte:

Python String to Bytes:

Converting Python strings to Bytes has become quite popular after the release of Python 3. This is largely because a lot of file handling and Machine learning methods require you to convert them. Before we dive into how to convert them let us first understand what they are and how they are different.

In Python 2, string and bytes were the same typeByte objects; however after the introduction of Python 3 Byte objects are considered as a sequence of bytes, and strings are considered as a sequence of characters. In essence, strings are human-readable and in order for them to become machine-readable, they must be converted to byte objects. This conversion also enables the data to be directly stored on the disk.

The process of converting string objects to byte objects is called encoding and the inverse is called decoding. We look at methods to achieve this below.

Method to convert strings to bytes:

There are many methods that can be used to convert Python string to bytes, however, we look at the most common and simple methods that can be used.

Using bytes():

The bytes() method is an inbuilt function that can be used to convert objects to byte objects.

The bytes take in an object (a string in our case), the required encoding method, and convert it into a byte object. The bytes() method accepts a third argument on how to handle errors.

Let us look at the code to convert a Python string to bytes. The encoding type we use here is “UTF-8”.

#Using the byte() method # initializing string str_1 = "Join our freelance network" str_1_encoded = bytes(str_1,'UTF-8') #printing the encode string print(str_1_encoded) #printing individual bytes for bytes in str_1_encoded: print(bytes, end = ' ') 
b'Join our freelance network' 74 111 105 110 32 111 117 114 32 102 114 101 101 108 97 110 99 101 32 110 101 116 119 111 114 107 

As you can see this method has converted the string into a sequence of bytes.

Note: This method converts objects into immutable bytes, if you are looking for a mutable method you can use the bytearray() method.

Using encode():

The encode() method is the most commonly used and recommended method to convert Python strings to bytes. A major reason is that it is more readable.

string.encode(encoding=encoding, errors=errors) 

Here, string refers to the string you are looking to convert.

  1. Encoding — Optional. The encoding method you are looking to use. After Python 3, UTF-8 has become the default.
  2. Error — Optional, A string containing the error message.
#Using the encode method # initializing string str_1 = "Join our freelance network" str_1_encoded = str_1.encode(encoding = 'UTF-8') #printing the encode string print(str_1_encoded) #printing individual bytes for bytes in str_1_encoded: print(bytes, end = ' ') 
b'Join our freelance network' 74 111 105 110 32 111 117 114 32 102 114 101 101 108 97 110 99 101 32 110 101 116 119 111 114 107 
#Using the encode method #initializing string str_1 = "Join our freelance network" str_1_encoded = str_1.encode(encoding = 'UTF-8') #printing the encode string print(str_1_encoded) #decoding the string str_1_decoded = str_1_encoded.decode() print(str_1_decoded) 
b'Join our freelance network' Join our freelance network 

Limitations and Caveats — Python String to Byte

  • Both the methods solve the same problem efficiently and choosing a particular method would boil down to one’s personal choice. However, I would recommend the second method for beginners.
  • The byte() method returns an immutable object. Hence, consider using the bytearray() if you are looking for a mutable object.
  • While using the byte() methods the object must have a size 0

Источник

Оцените статью