user3671325
user3671325

Reputation: 336

How to work with hex() in python?

I've problem with hex() in python 2.7 I want to convert '0777' to hex with user input. but it have problem with using integer with user input.

In [1]: hex(0777)
Out[1]: '0x1ff'

In [2]: hex(777)
Out[2]: '0x309'

In [3]: z = raw_input('enter:')
enter:0777

In [4]: z
Out[4]: '0777'

In [5]: hex(z)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-3682d79209b9> in <module>()
----> 1 hex(z)


TypeError: hex() argument can't be converted to hex

In [6]: hex(int(z))
Out[6]: '0x309'

In [7]:

I need 0x1ff but its showing me 0x309, how i can fix it ?

Upvotes: 1

Views: 2667

Answers (2)

vaultah
vaultah

Reputation: 46513

The base argument of the int class defaults to 10

int(x, base=10) -> integer

leading zeroes will be stripped. See this example:

In [1]: int('0777')
Out[1]: 777

Specify base 8 explicitly, then the hex function will give you the desired result:

In [2]: hex(int('0777', 8))
Out[2]: '0x1ff'

Upvotes: 4

Assem
Assem

Reputation: 12077

You can use input() instead of raw_input() to eval input and read octal values.

In [3]: z = input('enter:')
enter:0777

In [4]: z
Out[4]: 511

In [5]: hex(z)'
Out[5]: '0x1ff'

Upvotes: 0

Related Questions