Print strings to hexadecimal in Python
You can use one of the following two methods to convert and print a python string as an hexadecimal:
- Convert the Python string to an integer, using the int() function, and then convert to an hexadecimal using hex().
- Turn the string to an integer using the literal_eval function (from the ast Python module) and then cast to hexadecimal.
# 1: Using the int() function:
Using int(string, base=16) , we can convert the string to an integer with base 16 (Hexadecimal). Once we have the integer, we can use the inbuilt hex() function to convert an integer to a Hexadecimal number. So when we get a string, we will initially convert the string to an integer. We will then convert the integer value to hexadecimal using the function hex(). Let us see it in action.
Code:
def get_hex(value):
convert_string = int(value, base=16)
convert_hex = hex(convert_string)
return convert_hex, convert_string
userstring = "0XABC"
convert_hex, convert_string = get_hex(userstring)
print("String to Integer:",convert_string)
print("Integer to Hex:",convert_hex)
Output:
String to Integer: 2748
Integer to Hex: 0xabc
# 2: Using ast.literal_eval() function:
Using the literal_eval from the ast library, we can easily get the string and convert it to an integer. Then we can use the hex() function to get the Hexadecimal value. All we have to do is that we will need to import the literal_eval function from ast. Let us look at an example.
Code:
from ast import literal_eval
def get_hex(value):
convert_string = literal_eval(value)
convert_hex = hex(convert_string)
return convert_hex, convert_string
userstring = "0xabc"
convert_hex, convert_string = get_hex(userstring)
print("String to Integer:",convert_string)
print("Integer to Hex:",convert_hex)
Output:
String to Integer: 2748
Integer to Hex: 0xabc
Print string as bytes in Python
In order to cast and print a Python string to bytes, use the bytes() function, as shown in the code below:
file_str = 'Python string object'
print (bytes (file_str, encoding='windows-1255'))
Note: Use the decode() function to turn bytes to a string object.
Follow up learning
- To learn more about Python data type conversions, read our tutorial on converting string to lists in Python 3.