How do i print a hex value without 0x in python?

Besides going through string formatting, it is interesting to have in mind that when working with numbers and their hexadecimal representation we usually are dealing with byte-content, and interested in how bytes relate.

The bytes class in Python 3 had been enriched with methods over the 3.x series, and int.to_bytes combined with the bytes.hex[] provide full control of the hex-digits output, while preserving the semantics of the transform [not to mention, holding the intermediate "bytes" object ready to be used in any binary protocol that requires the number]:

In [8]: i = 3735928559

In [9]: i.to_bytes[4, "big"].hex[]
Out[9]: 'deadbeef'

Besides that, bytes.hex[] allow some control over the output, such as specifying a separator for the hex digits:

In [10]: bytes.hex?
Docstring:
Create a string of hexadecimal numbers from a bytes object.

  sep
    An optional single character or byte to separate hex bytes.
  bytes_per_sep
    How many bytes between separators.  Positive values count from the
    right, negative values count from the left.

Example:
>>> value = b'\xb9\x01\xef'
>>> value.hex[]
'b901ef'
>>> value.hex[':']
'b9:01:ef'
>>> value.hex[':', 2]
'b9:01ef'
>>> value.hex[':', -2]
'b901:ef'

[That said, in most scenarios just a quick print is wanted, I'd probably just go through f-string formatting, as in the accepted answer: f"{mynumber:04x}" - for the simple reason of "less things to remember"]

  • Problem Formulation
  • Method 1: Slicing
  • Method 2: Slicing + zfill[]
  • Method 3: Negative Hex Numbers
  • Where to Go From Here?
  • Programming Humor

Problem Formulation

If you print a hexadecimal number, Python uses the prefix '0x' to indicate that it’s a number in the hexadecimal system and not in the decimal system like normal integers.

print[hex[42]]
# 0x2a

However, if you already know that the output numbers are hexadecimal, you don’t necessarily need the '0x' prefix.

How to print hex numbers without the '0x' prefix?

Method 1: Slicing

To skip the prefix, use slicing and start with index 2 on the hexadecimal string. For example, to skip the prefix '0x' on the result of x = hex[42] ='0x2a', use the slicing operation x[2:] that results in just the hexadecimal number '2a' without the prefix '0x'.

x = hex[42]

print[x]
# 0x2a

print[x[2:]]
# 2a

Feel free to dive into the hex[] built-in function in this video tutorial:

Python hex[] Function – Not a Magic Trick

But what if you actually want to replace the prefix '0x' with the prefix '00' so that the resulting string has the same length?

Method 2: Slicing + zfill[]

The Python string.zfill[] method fills the string from the left with '0' characters. In combination with slicing from the third character, you can easily construct a hexadecimal string without leading '0x' characters and with leading '0' characters up to the length passed into the string.zfill[length] method.

print[hex[42][2:].zfill[4]]
# 002a

Alternatively, if you want to create a string with 8 characters, use string.zfill[8]:

print[hex[42][2:].zfill[8]]
# 0000002a

You can learn more about zfill[] in this video about Python string methods:

Python String Methods [Ultimate Guide]

Method 3: Negative Hex Numbers

If you need to handle negative hexadecimal numbers, the above methods do not work because the hex number now needs to replace the second and third character '0x'. For example, the hexadecimal number hex[-42] is '-0x2a'. You cannot simply skip the first two characters to obtain the correct result, can you? At the same time, if you always skipped or replaced the second and third characters, it wouldn’t work for positive numbers either. So what to do?

To print a positive or negative hexadecimal without the '0x' or '-0x' prefixes, you can simply use the string.replace['x', '0'] method and replace each occurrence of 'x' with '0'. The resulting string is mathematically correct because leading '0's don’t change the value of the number.

# Negative Hexadecimal
print[hex[-42].replace['x', '0']]
# -002a


# Positive Hexadecimal
print[hex[42].replace['x', '0']]
# 002a

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Programming Humor

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How can I print hexadecimal without 0x?

To print a positive or negative hexadecimal without the '0x' or '-0x' prefixes, you can simply use the string. replace['x', '0'] method and replace each occurrence of 'x' with '0' . The resulting string is mathematically correct because leading '0' s don't change the value of the number.

How do you remove an ox from hex in Python?

Use string formatting. – spectras. ... .
In Python3.6: val1 = f'{100:x}' – Robᵩ ... .
@Skitzafreak> full code with string formatting: "{:x}{:x}{:x}". format[val1, val2, val3] . ... .
Change the format specifier from x to 02x as explained in this answer to python hexadecimal. ... .
@StevenRumbalski Done!.

How do you print a hex value in Python?

Python: hex[] function.
Version: ... .
Syntax: hex[x].
Parameter: ... .
Example: Python hex[] function number = 127 print[number, 'in hex =', hex[number]] number = 0 print[number, 'in hex =', hex[number]] number = -35 print[number, 'in hex =', hex[number]] returnType = type[hex[number]] print['Return type from hex[] is', returnType].

What is the 0x in front of hexadecimal?

The prefix 0x is used in code to indicate that the number is being written in hex.

Chủ Đề