int to string conversion: newbie question
Alex Martelli
aleax at aleax.it
Mon Mar 24 08:13:01 EST 2003
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'
[Note for the unwary: recreational value only!!!]
Alex
More information about the Python-list
mailing list