Python hex() Function

Python3 内置函数Python3 Built-in Functions


hex()It is a built-in function in Python used to convert an integer to a hexadecimal string.

Hexadecimal is a commonly used numeral system in computers, where digits 0-9 and letters a-f represent values 10-15.hex()The function is commonly used in scenarios such as debugging, color codes, memory addresses, etc.

Word Definition: hexIt is the abbreviation for hexadecimal.


Basic Syntax and Parameters

Syntax Format

hex(x)

Parameter Description

  • Parameter x:
    • Type: Integer
    • Description: The integer to be converted to hexadecimal.

Function Description

  • Return Value: Returns a hexadecimal string starting with "0x".

Examples

Example 1: Basic Usage

Example

# Basic conversion
print(hex(10))     # Output: 0xa
print(hex(255))    # Output: 0xff
print(hex(256))    # Output: 0x100

# Negative numbers (will display a minus sign)
print(hex(-10))    # Output: -0xa
print(hex(-255))   # Output: -0xff

# Zero
print(hex(0))      # Output: 0x0

# Large number
print(hex(16))     # Output: 0x10
print(hex(255))    # Output: 0xff
print(hex(4096))   # Output: 0x1000

Expected output:

0xa
0xff
0x100
-0xa
-0xff
0x0
0x10
0xff
0x1000

Code Analysis:

  1. The returned string starts with "0x", indicating hexadecimal.
  2. Letters use lowercase (a-f) by default.
  3. Negative numbers display a minus sign.

Example 2: Practical Application

Example

# Color code conversion
r, g, b = 255, 128, 0
color = f"#{hex(r)[2:]:0>2}{hex(g)[2:]:0>2}{hex(b)[2:]:0>2}"
print(color)  # Output: #ff8000

# Using formatting
print(f"{10:#x}")    # Output: 0xa
print(f"{255:#x}")   # Output: 0xff
print(f"{255:x}")   # Output: ff

# Remove the 0x prefix
s = hex(255)
print(s[2:])         # Output: ff
print(s.replace("0x", ""))  # Output: ff

Expected output:

#FF8000
0xa
0xff
ff
ff
ff

Hexadecimal is commonly used in scenarios such as color codes, debug output, etc.


Python3 内置函数Python3 Built-in Functions


Other Extensions