1

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 ?

3
  • So you want octal to hex? What if a user enters 777? Commented May 17, 2015 at 11:16
  • so you specifically only want octal input? int('8',8) -> error Commented May 17, 2015 at 11:23
  • You have to exactly indicate octal digit hex(0o777) Commented May 17, 2015 at 11:45

2 Answers 2

4

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'
Sign up to request clarification or add additional context in comments.

Comments

0

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'

3 Comments

Don't useinput ever
if his input is trust-able, why not?
how do you make user input trust-able?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.