- How can I convert string variable into byte type in python? [duplicate]
- 2 Answers 2
- How to convert a string to bytes in Python?
- What are Strings an Bytes ?
- Strings
- Frequently Asked:
- Bytes
- Convert String to Bytes using bytes() method
- Convert String to Bytes using encode() method
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- How to convert Python string to bytes?
- Table of Contents — Python String to Byte
- Python String to Bytes:
- Method to convert strings to bytes:
- Using bytes():
- Syntax of bytes():
- Using encode():
- Syntax of encode():
- Parameters:
- Code to convert a python string to bytes:
- Limitations and Caveats — Python String to Byte
How can I convert string variable into byte type in python? [duplicate]
I want to encrypt a messages which I got from user input using Cryptography: I have the following simple code:
import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend backend = default_backend() messages = input("Please, insert messages to encrypt: ") key = os.urandom(24) print(key) cipher = Cipher(algorithms.TripleDES(key), modes.ECB(), backend=backend) encryptor = cipher.encryptor() cryptogram = encryptor.update(b"a secret message") + encryptor.finalize() print(cryptogram)
When I hard code the messages «a secret message» with b prefix in the code it works fine. What I wanted to do is to use messages variable to get the text from user input.
messages = input("Please, insert messages to encrypt: ")
I’ve tried several ways to covert the string type from the input to byte type and pass it to encryptor.update method but nothing works for me.
messages = input(b"Please, insert messages to encrypt: ") cryptogram = encryptor.update(byte, message) + encryptor.finalize() .
This was trivial to search. Please look for a duplicate question the next time. It will save you the effort of writing up a long question and us the effort of closing it.
2 Answers 2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 2 13:23:27 2018 @author: myhaspl @email:myhaspl@myhaspl.com @blog:dmyhaspl.github.io """ import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import padding padder = padding.PKCS7(128).padder() backend = default_backend() key = os.urandom(32) iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) encryptor = cipher.encryptor() messages = input("Please input your message: ") messages=bytes(messages,"utf-8") padded_data = padder.update(messages ) padded_data += padder.finalize() print(padded_data) ct = encryptor.update(padded_data) + encryptor.finalize() decryptor = cipher.decryptor() decryptorData=decryptor.update(ct) + decryptor.finalize() unpadder = padding.PKCS7(128).unpadder() data = unpadder.update(decryptorData) print(data + unpadder.finalize()) Please input your message: hello,world! I am dmyhaspl.my blog is dmyhaspl.github.io b'hello,world! I am dmyhaspl.my blog is dmyhaspl.github.io\x08\x08\x08\x08\x08\x08\x08\x08' b'hello,world! I am dmyhaspl.my blog is dmyhaspl.github.io' >>>
How to convert a string to bytes in Python?
In this article, we will discuss what are Bytes and String, and also we will learn how to convert string to bytes using python.
Table Of Contents
Before Python3, the strings and bytes were of same object type, which is type Byte. But now in Python 3, we have Bytes which are sequence of Bytes and strings are sequence of characters. Strings are not machine readable. In order to store them on disk we need to convert them to bytes.
What are Strings an Bytes ?
Strings
A String is an array of bytes representing Unicode characters enclosed in single, double or triple quotes. The Enclosed characters can be any digit, alphabets or special symbols. A String is just normal text in human readable format. Also, strings are immutable, it means once defined then they can not be changed.
Frequently Asked:
strValue = 'String Example' print(strValue) # type() will print the data type print(type(strValue))
Bytes
Whenever we find a prefix ‘b’ in front of any string, it is reffered as byte string in python. Bytes are not human readable, machines like our computers can understand them easily and interprets them as human readable.
byteValues = b'Bytes example' print(byteValues) # type() will print the data type print( type(byteValues) )
So, we know about strings and bytes data types. Now we will look into the methods through which we can covert strings to bytes. We have different methods for this conversion in python, we will look them one by one.
Always try examples in your machine. Just copy and paste code and play around with it. We have used Python 3.10.1 for writing example codes. To check your version write python –version in your terminal.
Convert String to Bytes using bytes() method
The bytes() method is a built-in method in Python, and it recieves three parameters :
- First is string which needs to converted to bytes.
- Second is method of encoding. Here we will be using utf-8. You need to provide a encoding method otherwise it will throw TypeError .
- There are other methods of encoding like UTF-16,Latin-1.Feel free to use other encoding methods depending on your use.
strValue = 'I am Happy ?' print(strValue) # type() will print data type of strValue print(type(strValue)) # Convert string to bytes bytesValue = bytes(strValue,'UTF-8') print(bytesValue) # type() will print data type of bytesValue print(type(bytesValue))
I am Happy ? b’I am Happy \xf0\x9f\x98\x8a’
You can see we have used byte() method to convert string to bytes.
Convert String to Bytes using encode() method
The encode() is a built-in method of Python, and it is most commonly used to convert bytes to string. As we know that the word encode means encrypting, which means to encrypt a data to machine readable format, that cannot easily be understood by humans.
It recieves two parameters :
– First is the encoding method which is optional in encode() method and in python 3 default method of encoding is ‘UTF-8’.
– Second is error handling or a error message in form of string which is also an optional.str.encode(encoding='UTF-8', error)
str here is string variable which needs to be converted to bytes.
strValue = 'I am using encode method ??' print(strValue) #type() will output the data type of strValue print(type(strValue)) # Convert string into bytes using encode() method bytesValue = strValue.encode() # type() will output the data type of bytesValue print(type(bytesValue)) print(bytesValue)
I am using encode method ?? b'I am using encode method \xf0\x9f\x91\x87\xf0\x9f\x91\x87'
So here we used encode() method to convert strings to bytes.
In this article we used two different methods to convert a given string into bytes data type. You can always use both but the easiest and most common used method is encode() method, because you do not need to provide any error handling or encoding method in it. But if you don’t provide any of these in bytes() method, you will face TypeError .
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
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. This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
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.
Syntax of bytes():
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.
Syntax of encode():
string.encode(encoding=encoding, errors=errors)
Here, string refers to the string you are looking to convert.
Parameters:
- Encoding — Optional. The encoding method you are looking to use. After Python 3, UTF-8 has become the default.
- Error — Optional, A string containing the error message.
Code to convert a python string to bytes:
#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 = ' ')
The output is the same as above.
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
Similar to the encode() method, the decode() method can be used to convert bytes to strings.
#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