[Python-Dev] str with base (original) (raw)

Bob Ippolito bob at redivi.com
Thu Jan 19 21:44:09 CET 2006


On Jan 19, 2006, at 11:12 AM, Guido van Rossum wrote:

On 1/19/06, Fredrik Lundh <fredrik at pythonware.com> wrote:

Guido van Rossum wrote:

I think we ought to let this sit for a while and come back to it in a few week's time. Is 'base' really the right name? It could just as well be considered a conversion in the other direction. the same applies to hex and oct, of course. Right. And this is not a hypothetical issue either -- in Perl, hex and oct do work the other way I believe. More reasons to get rid of these in Python 3000. Perhaps we should also get rid of hex/oct lterals?

In Perl, hex(n) is like int(n, 16) and oct(n) is like int(n, 8) --
but they "try very hard" to make sense out of the given scalar (e.g.
more like int(n, 0) with a suggestion for base).

$ perl -e 'print hex("12") . " " . oct("12") . " " . oct("0x12") . "
" . hex("fubar")' 18 10 18 15

If you notice, oct("0x12") gives the hexadecimal result, and the
functions will try and make a value even out of garbage data.

In Ruby, you have the optional radix argument to_s and to_i, where
to_i will just return 0 for invalid values. They will take any radix
from 2..36.

$ irb irb(main):001:0> 12.to_s => "12" irb(main):002:0> 12.to_s(16) => "c" irb(main):003:0> 12.to_s(8) => "14" irb(main):004:0> "12".to_i(8) => 10 irb(main):005:0> "12".to_i(16) => 18 irb(main):006:0> "0x12".to_i(16) => 18 irb(main):007:0> "0x12".to_i(8) => 0 irb(main):008:0> "0x12".to_i => 0 irb(main):009:0> "fubar".to_i => 0 irb(main):010:0> "fubar".to_i(36) => 26608563

-bob



More information about the Python-Dev mailing list