int to string conversion: newbie question

Dan Bishop danb_83 at yahoo.com
Tue Mar 25 07:16:13 CET 2003

```"Anna" <revanna at mn.rr.com> wrote in message news:<pan.2003.03.25.03.42.38.942175 at mn.rr.com>...
> 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?
> >>
> >>
> >> >>> '%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?

strnum = lambda n: (n < 0 and ['-' + strnum(-n)] or [(n < 10 and
[chr(ord('0') + n)] or [strnum(n // 10) + strnum(n % 10)])[0]])[0]

```