Content · Programming · Python

Python hex() Function: Usage and Examples

hex(integer) returns a string representation of an integer in base 16 (hexadecimal). Its usual output includes the 0x prefix so the base is visible. It does not change the integer itself. See two practical examples.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

You are inspecting the low-level representation of permissions, bit masks or identifiers.

What You Need to Understand


hex(integer) returns a string representation of an integer in base 16 (hexadecimal). Its usual output includes the 0x prefix so the base is visible. It does not change the integer itself.

When to Use It


You are inspecting the low-level representation of permissions, bit masks or identifiers.

Step-by-Step Python Example


number = 255
print(hex(number))
print(hex(-number))
print(type(hex(number)).__name__)

How the Example Works


The function returns text, including a sign for a negative value. The last line prints str, showing that the result is not an integer.

Example Output


0xff
-0xff
str
ff

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

number = 255
formatted = format(number, "x")
print(formatted)

Important Behavior and Edge Cases


Use int(text, base) when converting a formatted representation back to a number. Leading prefixes are not regular digits in the corresponding base.

Try It Yourself


Convert the integer 64 and explain the prefix in the output.

Common Beginner Mistakes


  • Use int(text, base) when converting a formatted representation back to a number. Leading prefixes are not regular digits in the corresponding base.
  • Applying a string method before defining whether text is intended for display, comparison, parsing, or input validation.

Key Takeaways


  • hex(integer) returns a string representation of an integer in base 16 (hexadecimal).
  • The function returns text, including a sign for a negative value.
  • Use int(text, base) when converting a formatted representation back to a number.
Share this resourceSend this page to someone who may find it useful.