Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #84006
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: How to change the number into the same expression's string and vice versa? |
| Date | 2015-01-19 10:24 +0100 |
| Organization | None |
| References | <CA+YdQ_651X0NDPw1j203WGbeDTxy_Mw7g0w3VH1WoaGR1iv-Cg@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.17846.1421659473.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: How to change the number into the same expression's string and vice versa? Peter Otten <__peter__@web.de> - 2015-01-19 10:24 +0100
Re: How to change the number into the same expression's string and vice versa? Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2015-01-19 11:36 +0200
Re: How to change the number into the same expression's string and vice versa? Peter Otten <__peter__@web.de> - 2015-01-19 12:46 +0100
csiph-web