--
-----------------------------------------------------------------------
| absolute zero is real cool |
| |
| heuv...@nlr.nl |
| |
-----------------------------------------------------------------------
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
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'
>>>
> 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
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
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
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_
: 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
Isn't the answer just to either use...
intVar = 12345
str = repr(intVar)
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.
--
A.M. Kuchling http://starship.skyport.net/crew/amk/
Things are not as bad as they seem. They are worse.
-- Bill Press
Please ignore my last post. It bombed half way through and only posted the
beginning of my post.
I was saying...
It did it again. Email me if it happens this time. I give up if it happens
again.
I was saying...
> 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
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
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)
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.)
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.
>
[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