How to Print a Variable in Hexadecimal in Python?

Estimated read time 2 min read

To print a variable in hexadecimal format in Python, you can use the built-in hex() function. The hex() function takes an integer argument and returns a string representation of the integer in hexadecimal format. Here’s an example code snippet that shows how to print a variable in hexadecimal format:

# Define an integer variable
my_var = 42

# Print the variable in hexadecimal format
print(hex(my_var))

In this example, the my_var variable is an integer variable that contains the value 42. The hex() function is used to convert the integer to a hexadecimal string, and the resulting string is printed using the print() function. The output will be 0x2a, which is the hexadecimal representation of the integer 42.

If you want to remove the 0x prefix from the output, you can use string slicing to print only the hexadecimal digits:

# Define an integer variable
my_var = 42

# Print the variable in hexadecimal format without the 0x prefix
print(hex(my_var)[2:])

In this example, the hex() function is used to convert the integer my_var to a hexadecimal string, and the [2:] slice notation is used to remove the first two characters (0x) from the string. The resulting string contains only the hexadecimal digits and is printed using the print() function. The output will be 2a, which is the hexadecimal representation of the integer 42 without the 0x prefix.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply