Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of 0x and \x in python hex strings?

Tags:

python

hex

numpy

I'm doing some binary operations which are often shown as hex-es. I have seen both the 0x and \x as prefixes.

In which case is which used?

like image 864
TheMeaningfulEngineer Avatar asked Jun 03 '13 18:06

TheMeaningfulEngineer


People also ask

What does 0x mean in Python?

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.

What does 0x mean in hex?

The prefix we use for hexadecimal is "0x". To represent the numbers 0-9, we simply use those digits. To represent 10-15, we use the letters A-F. A.

What are 0x prefixed hex strings?

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

How do I print a hex value without 0x in Python?

Since Python returns a string hexadecimal value from hex() we can use string. replace to remove the 0x characters regardless of their position in the string (which is important since this differs for positive and negative numbers).


1 Answers

0x is used for literal numbers. "\x" is used inside strings to represent a character

>>> 0x41
65
>>> "\x41"
'A'

>>> "\x01" # a non printable character
'\x01'
like image 182
John La Rooy Avatar answered Oct 02 '22 15:10

John La Rooy