Inverse of int(s, base)?

Oliver Fromme olli at secnetix.de
Tue May 11 07:26:50 EDT 2004


Paul Rubin <http://phr.cx@nospam.invalid> wrote:
 > danb_83 at yahoo.com (Dan Bishop) writes:
 > > [...]
 > > That works (for positive integers), but it might be more efficient to
 > > not create a new string each time through the loop.  An alternative is:
 > > 
 > > def str_base(n, base=10):
 >   ...
 > 
 > Similarly:
 > 
 > def str_base(n, base=10):
 >    results = []
 >    sign,n = ('','-')[n < 0], abs(n)
 >    while n:
 >        n, r = divmod(n, base)
 >        results.append(str_digits[r])
 >    results.reverse()
 >    return sign + ''.join(results)

Cool, thanks both of you!  Using divmod() is a good idea.

Is creating strings really that expensive in Python?  I'm
surpised that you're saying that modifying a list and then
calling reverse() and join() is more efficient.  I thought
that the overhead of compound objects such as lists is
more expensive than creating strings, which I thought where
rather "cheap and simple".

I work with strings a lot (in scripts for administration,
CGI programs etc.).  And since strings are immutable, I
often have to create new ones.  Now do you suggest I should
reconsider my approach and rather try to work with lists in
general, and only convert them back to strings for output
at the very end?

Best regards
   Oliver

-- 
Oliver Fromme, secnetix GmbH & Co KG, Oettingenstr. 2, 80538 Munich
Any opinions expressed in this message may be personal to the author
and may not necessarily reflect the opinions of secnetix in any way.

(On the statement print "42 monkeys" + "1 snake":)  By the way,
both perl and Python get this wrong.  Perl gives 43 and Python
gives "42 monkeys1 snake", when the answer is clearly "41 monkeys
and 1 fat snake".        -- Jim Fulton



More information about the Python-list mailing list