Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

converting integer to string

778 views
Skip to first unread message

M.J. Heuveling

unread,
Oct 6, 1998, 3:00:00 AM10/6/98
to
Is there a function in Python to convert an integer value to a string?
I want to add the integer to a string, so it has to be converted.

--
-----------------------------------------------------------------------
| absolute zero is real cool |
| |
| heuv...@nlr.nl |
| |
-----------------------------------------------------------------------

Michael Hudson

unread,
Oct 6, 1998, 3:00:00 AM10/6/98
to
"M.J. Heuveling" <heuv...@nlr.nl> writes:
> Is there a function in Python to convert an integer value to a string?
> I want to add the integer to a string, so it has to be converted.

Several:
(assume i is an integer)

str(i)
repr(i) or `i` (those are equivalent)
'%d'%i

Hope this helps

--
Michael Hudson
Jesus College
Cambridge
mw...@cam.ac.uk

Michael McLay

unread,
Oct 6, 1998, 3:00:00 AM10/6/98
to
M.J. Heuveling writes:
> Is there a function in Python to convert an integer value to a string?
> I want to add the integer to a string, so it has to be converted.

There are several ways to convert numbers to strings. The first
example below is described on page 21 of the Library Reference.

~: python
Python 1.5.1 (#1, May 6 1998, 01:48:27) [GCC 2.7.2.3] on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> str(2)
'2'
>>> b = 2
>>> "string"+ `b`+"more"
'string2more'
>>> "string%dmore" %b
'string2more'
>>> "string%smore" %b
'string2more'
>>>


Erik Brozek

unread,
Oct 6, 1998, 3:00:00 AM10/6/98
to M.J. Heuveling
M.J. Heuveling wrote:

> Is there a function in Python to convert an integer value to a string?
> I want to add the integer to a string, so it has to be converted.

str_value = str(int_value)
module string http://www.python.org/doc/lib/module-string.html


Tim Peters

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
> Is there a function in Python to convert an integer value to
> a string?

This is my favorite:

def int2str(n):
import sys
import tempfile
import os
answer = "*** error ***"
name = tempfile.mktemp()
try:
f = open(name, "w")
sys.stdout = f
print n
f.close()
f = open(name, "r")
answer = f.readline()[:-1]
f.close()
finally:
sys.stdout = sys.__stdout__
try:
f.close()
except:
pass
try:
os.remove(name)
except:
pass
assert answer == str(n)
return answer

tongue-in-cheek-but-not-sure-whose-ly y'rs - tim

Fredrik Lundh

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
Tim Peters <tim...@email.msn.com> wrote:
>> Is there a function in Python to convert an integer value to
>> a string?
>
>This is my favorite:

With PIL 0.3b3 or later, you can do that in far less lines:

def int2str(n):
import Image, string
image = Image.new("L", (len(str(n)), 1), None)
for i in range(image.size[0]):
n, d = divmod(n, 10)
image.putpixel((i, 0), ord(string.digits[int(d)]))
return image.transpose(Image.FLIP_LEFT_RIGHT).tostring()

Slightly more obscure, but it uses a few fancy tricks like
"for in range", "divmod", and the Image "transpose" stuff.
And it almost works correctly for long integers too.

Cheers /F
fre...@pythonware.com
http://www.pythonware.com


Andrew M. Kuchling

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
Tim Peters quoted:

>> Is there a function in Python to convert an integer value to
>> a string?

Here's an XML-based variant; the integer is marshalled into a simple
format, and the resulting XML file is then parsed into a Document
Object Model Tree. Obtaining the string value is then simply a matter
of retrieving the single 'integer' element in the tree, and getting
the value of its first child, which must be a Text node.

A useful property of this implementation is that it will return the
string value of the first integer in a tuple or list. Actually,
given a recursive data structure, it should return the string value of
the first integer found in a preorder traversal of the list.

So, for example:

print `xml_int2str( 5 )`
print `xml_int2str( (6,5) )`
print `xml_int2str( ("stupid string", 7,5) )`

outputs

'5'
'6'
'7'

def xml_int2str(n):
# Marshal the integer, sticking the result in a StringIO object.
import StringIO
mem_file = StringIO.StringIO()
from xml import marshal
data = marshal.dump( n, mem_file )
mem_file.seek(0)

# mem_file now contains something like:
# <?xml version="1.0"?>
# <!DOCTYPE marshal SYSTEM "marshal.dtd">
# <marshal><integer>5</integer></marshal>
# Parse this and convert it to a DOM tree.
from xml.sax import saxexts
from xml.dom.sax_builder import SaxBuilder
p = saxexts.make_parser()
dh = SaxBuilder()
p.setDocumentHandler(dh)
p.parseFile( mem_file )

# Get the root Document node.
doc = dh.document

# List all the 'integer' elements in the tree, and retrieve the
# value of the child of the first one, which should be a Text node
# containing the string '5'.
integer_list = doc.getElementsByTagName( 'integer' )
integer_elem = integer_list[0]
children = integer_elem.get_childNodes()
return children[0].get_nodeValue()

--
A.M. Kuchling http://starship.skyport.net/crew/amk/
REMIND ME AGAIN, he said, HOW THE LITTLE HORSE-SHAPED ONES MOVE.
-- Death on symbolic last games, in Terry Pratchett's _Small Gods_


Michael P. Reilly

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
Andrew M. Kuchling <akuc...@cnri.reston.va.us> wrote:
: Tim Peters quoted:

: So, for example:

: outputs

: '5'
: '6'
: '7'

Gee.... sounds like we have the makings of a Python Obfuscated Contest,
like Perl. *Shudder* (And I thought I got that all out of my system
ten years ago with the C contest.)

-Arcege

Robert Roberts

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
Did I misunderstand the question?

Isn't the answer just to either use...

intVar = 12345
str = repr(intVar)


Andrew M. Kuchling

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
Michael P. Reilly writes:
>Gee.... sounds like we have the makings of a Python Obfuscated Contest,
>like Perl. *Shudder* (And I thought I got that all out of my system
>ten years ago with the C contest.)

Python people seem to do something a bit different, probably
because obfuscating Python code is somewhat boring; you just use
lambda a lot. Instead, we occcasionally have threads where people do
something simple in the most overcomplicated, Rube Goldberg way that
the writer can think of.

Whatever you do, don't look at either
http://www.python.org/doc/FAQ.html#4.15 and
http://starship.skyport.net/crew/amk/writing/crypto-curiosa.html .

ObInt2Str: here's a probabilistic algorithm for converting an
integer to a string:

import whrandom
NUM_DIGITS = 5

def int2str(n):
while (1):
# Generate a random string of digits, NUM_DIGITS long.
s = ""
for i in range( NUM_DIGITS ):
s = s + whrandom.choice('0123456789')

# Does the string have the same numeric value of n?
# It must be the right answer, then!
if int(s) == n: return s

Pretty speedy for small values of NUM_DIGITS.

Things are not as bad as they seem. They are worse.
-- Bill Press


Robert Roberts

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
Don't you hate it when that happens?

Please ignore my last post. It bombed half way through and only posted the
beginning of my post.

I was saying...


Robert Roberts

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
str = `intVal`

robert_j...@rl.gov

It did it again. Email me if it happens this time. I give up if it happens
again.

I was saying...


Robert Roberts

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to

Gordon McMillan

unread,
Oct 7, 1998, 3:00:00 AM10/7/98
to
At one time or another, and in a barrage of "I can do it more
bizzarely than you" posts, Robert Roberts came up with:

> str = repr(intVal)
and
> str = `intVal`

Which are correct, but I wouldn't put the value in 'str' because you
are using the name of a built-in function that does - guess what?

Let's just say there are SO MANY ways to do what you want that some
probably couldn't believe your question was serious...

- Gordon

Tim Peters

unread,
Oct 8, 1998, 3:00:00 AM10/8/98
to
[Gordon McMillan]

> At one time or another, and in a barrage of "I can do it more
> bizzarely than you" posts, Robert Roberts came up with:
>
> > str = repr(intVal)
> and
> > str = `intVal`
>
> ...

> Let's just say there are SO MANY ways to do what you want that some
> probably couldn't believe your question was serious...

Na, I started this particular joyous mess, and I knew he was serious. But
there were already three useful and correct responses to the original
question, so I had some fun with it instead. I did put "assert answer ==
str(n)" at the end of my function, so that the truly baffled yet persistent
would eventually get the joke.

looks-like-apology-is-striving-to-become-a-way-of-life<wink>-ly y'rs - tim

Greg Stein

unread,
Oct 8, 1998, 3:00:00 AM10/8/98
to
Andrew M. Kuchling wrote in message
<13851.37844....@amarok.cnri.reston.va.us>...

>Michael P. Reilly writes:
>>Gee.... sounds like we have the makings of a Python Obfuscated Contest,
>>like Perl. *Shudder* (And I thought I got that all out of my system
>>ten years ago with the C contest.)
>
> Python people seem to do something a bit different, probably
>because obfuscating Python code is somewhat boring; you just use
>lambda a lot. Instead, we occcasionally have threads where people do
>something simple in the most overcomplicated, Rube Goldberg way that
>the writer can think of.
>
> Whatever you do, don't look at either
>http://www.python.org/doc/FAQ.html#4.15 and
>http://starship.skyport.net/crew/amk/writing/crypto-curiosa.html .


Boring?!? Heh. Try this on for size. Cut and paste it into an interpreter,
all on one line (if you can't cut and paste, then don't try!).

f=lambda
x=['31312405171810171211313126112','7189749374747628707','9626701','88738091
95908988937382747529513','807979748182306979652922711','25141421122626106','
hi there!'],z=globals(),y=lambda x: reduce(lambda x,y:x+y,map(lambda
x,y=x,z=lambda
x:int(x[:2]):chr((z(y[x*int(y[-5]):])^z(y[-4:]))+z(y[-4:])),range(int(x[-2:]
)))):map(lambda
z,x=y,y=x,w=z:z(z(w[x(y[2])],x(y[3]))[0],x(y[5]))(x(y[4])),[vars(z[y(x[0])])
[y(x[1])]]) and x[-1];print f()

I tell you... writing that was far from boring!

Who said you couldn't obfuscate Python? :-)

The person to provide the first detailed description of how the above code
actually works will receive ten Python Guru Points!

-g

--
Greg Stein (gst...@lyra.org)


Tony J Ibbs

unread,
Oct 8, 1998, 3:00:00 AM10/8/98
to

"Tim Peters" <tim...@email.msn.com> wrote:
> I did put "assert answer == str(n)" at the end of my function, so that
> the truly baffled yet persistent would eventually get the joke.

but that was the bit that made me laugh out loud!

--
Tony J Ibbs (Tibs) http://www.tibsnjoan.demon.co.uk/
My views! Mine! Mine! (Unless Laser-Scan ask nicely to borrow them.)


Robert_J...@rl.gov

unread,
Oct 8, 1998, 3:00:00 AM10/8/98
to
Ok. So I'm appearing really slow.

I am a bit handicapped in that they do not allow us direct access to the
news server here from work. It's a long complicated story, but one of
the several contractors on site has the job of downloading the news.
When we make a post, it goes to them. They eventually get around to
moving our posts out. We don't always get a very up to date snapshot of
what's out there.

All I saw was one question and one answer that didn't finish on my
screen. I didn't even try to read it because I was too busy trying to
do what I actually get paid for. Then my post failed and posted a
partial answer and I got hung up in that.

Therefore, if you see one of my posts sometime and it looks like I have
know idea what's going one its probably only because I have no idea
what's going on.

Be gentle ;-)

Robert J. Roberts
LMSI-SDI
509.376.6343

> -----Original Message-----
> From: Tim Peters [SMTP:tim...@email.msn.com]
> Sent: Wednesday, October 07, 1998 11:20 PM
> To: gm...@hypernet.com; Robert Roberts; pytho...@cwi.nl
> Subject: RE: converting integer to string
>
> [Gordon McMillan]
> > At one time or another, and in a barrage of "I can do it more
> > bizzarely than you" posts, Robert Roberts came up with:
> >
> > > str = repr(intVal)
> > and
> > > str = `intVal`
> >
> > ...
> > Let's just say there are SO MANY ways to do what you want that some
> > probably couldn't believe your question was serious...
>
> Na, I started this particular joyous mess, and I knew he was serious.
> But
> there were already three useful and correct responses to the original

> question, so I had some fun with it instead. I did put "assert answer


> ==
> str(n)" at the end of my function, so that the truly baffled yet
> persistent
> would eventually get the joke.
>

Tim Peters

unread,
Oct 11, 1998, 3:00:00 AM10/11/98
to
[Tim]

> I did put "assert answer == str(n)" at the end of my function, so that
> the truly baffled yet persistent would eventually get the joke.

[Tibs]


> but that was the bit that made me laugh out loud!

Hmm -- now that you remind me of it, that *was* the joke! How soon the old
forget. Oh, and that "sys.stdout = sys.__stdout__" introduced the potential
for a huge but subtle bug in the name of "being safe".

I award the prize to Fredrik, though, who had the unmitigated gall to bury
str(n) *inside* his algorithm, with his

image = Image.new("L", (len(str(n)), 1), None)

line -- I'm still laughing over that one.

learning-not-to-make-bar-bets-with-crabby-swedes<wink>-ly y'rs - tim

0 new messages