How to change the number into the same expression's string and vice versa?

Peter Otten __peter__ at web.de
Mon Jan 19 10:24:17 CET 2015


contro opinion wrote:

> In the python3 console:
> 
>     >>> a=18
>     >>> b='18'
>     >>> str(a) == b
>     True
>     >>> int(b) == a
>     True
> 
> 
> Now how to change a1,a2,a3  into b1,b2,b3 and vice versa?
> a1=0xf4
> a2=0o36
> a3=011
> 
> b1='0xf4'
> b2='0o36'
> b3='011'

Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> "{:o}".format(0xf4)
'364'
>>> "{:x}".format(0xf4)
'f4'
>>> "{}".format(0xf4)
'244'

To add a prefix just put it into the format string.

You can specify the base for int() or trigger automatic base recognition by 
passing a base of 0:

>>> int("f4", 16)
244
>>> int("0xf4", 0)
244
>>> int("0o36", 0)
30

The classical prefix for base-8 numbers is no longer recognised in Python 3:

>>> int("011", 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: '011'
>>> int("011")
11
>>> int("011", 8)
9





More information about the Python-list mailing list