int to string conversion: newbie question

Anna revanna at mn.rr.com
Tue Mar 25 04:43:24 CET 2003


On Mon, 24 Mar 2003 13:13:01 +0000, Alex Martelli wrote:

> Neal Norwitz wrote:
> 
>> On Sat, 22 Mar 2003 14:16:59 -0500, Kristofer Wouk wrote:
>> 
>>>     I know I'm dumb, but I can't figure this out. How do I convert from
>>>     an int to a string?
>> 
>> Take your pick:
>> 
>> >>> '%s' % 53
>> '53'
>> >>> str(53)
>> '53'
>> >>> '%d' % 53
>> '53'
> 
> These are the best ways, but, just for fun, assuming the int is referred
> to by variable name x, let's add `x` (note the back-quotes) and repr(x)
> and of course, last but not least...:
> 
> def whyBeSimpleIfYouCanBeComplicated(x, base=10):
>     if not x: return '0'
>     zero = ord('0')
>     digits = []
>     while x:
>         x, dig = divmod(x, base)
>         digits.append( chr( zero + dig ) )
>     digits.reverse()
>     return ''.join(digits)
> 
> and the ever-popular recursive version:
> 
> def weirderThanThou(x, base=10):
>     zero = ord('0')
>     def recu(x):
>         if not x: return ''
>         x, dig = divmod(x, base)
>         return recu(x) + chr(zero+dig)
>     return recu(x) or '0'
 
well yes, but where's the ternary version and the lambda version?

Anna





More information about the Python-list mailing list