Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 hex() Function

The Python hex() function

Python3 Built-in Functions Python3 built-in function


hex() is a built-in Python function that converts an integer to a hexadecimal string.

Hexadecimal is a commonly used number representation in computing, with digits 0-9 and letters a-f representing 10-15.hex() The function is often used in debugging, color codes, memory addresses, and similar scenarios.

Word meaning: hex is short for hexadecimal.


Basic syntax and parameters

Syntax format


hex(x)

Parameter Description

- Type: integer - Description: the integer to convert to hexadecimal.

Function description


Example

Example 1: basic usage

Example

Basic conversions

print

(

hex

(

10

)

)

   

Output: 0xa

print

(

hex

(

255

)

)

   

Output: 0xff

print

(

hex

(

256

)

)

   

Output: 0x100

Negative numbers (a minus sign is shown)

print

(

hex

(

10

)

)

   

Output: -0xa

print

(

hex

(

255

)

)

 

Output: -0xff

zero

print

(

hex

(

0

)

)

     

Output: 0x0

Large numbers

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 are lowercase by default (a-f).
  3. Negative numbers show a minus sign.

Example 2: practical applications

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 often used in color codes, debug output, and similar scenarios.


Python3 Built-in Functions Python3 built-in function