Re: [Tutor] how to join two different files

2009-07-30 Thread wesley chun
>> Maybe you could break that up a bit? This is the tutor list, not a
>> one-liner competition!
>
> rather than one-liners, we can try to create the most "Pythonic" solution. 
> below's my entry. :-)
>
> myMac$ cat parafiles.py
> #!/usr/bin/env python
>
> from itertools import izip
> from os.path import exists
>
> def parafiles(*files):
>    vec = (open(f) for f in files if exists(f))
>    data = izip(*vec)
>    [f.close() for f in vec]
>    return data
>
> for data in parafiles('fileA.txt', 'fileB.txt'):
>    print ' '.join(d.strip() for d in data)

i proposed this problem as a code golfing competition to my
co-workers, and after tweaking it slightly to take filenames from the
command-line instead of as function parameters, i reduced my original
solution to:

from itertools import izip
from os.path import exists
from sys import argv

vec = (open(f) for f in argv[1:] if exists(f))
for d in izip(*vec):
print ' '.join(c.strip() for c in d)
for f in vec:
f.close()

if this was a code golf competition, and i was more careless about
leaking filehandles (or letting Python deal with it), i can actually
reduce it to an ugly (yet elegant) 1-liner serving as an example of
how *not* to code in production:

print '\n'.join(' '.join(c.strip() for c in d) for d in izip(*(open(f)
for f in argv[1:] if exists(f

note that the only list used here is sys.argv (using map() or
[listcomp] creates lists which use memory... superfluous if only
iterating across them once). anyway, please don't try this at work
folks. :-)

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Python Web Development with Django", Addison Wesley, (c) 2009
http://withdjango.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Currency conversion module in python

2009-07-30 Thread OkaMthembo
Hi Amit, this might be what you want..hopefully with a dollop of humor :)

http://lmgtfy.com/?q=currency+conversion+module+in+python&l=1

Cheers

On Thu, Jul 30, 2009 at 12:45 AM, Amit Sethi wrote:

> Hi , Does anybody know of any currency conversion module in python
>
> --
> A-M-I-T S|S
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Lloyd Dube
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] flag to call methods on objects?

2009-07-30 Thread prasad rao
hello
I wanted to prevent other users of my computers to read my files.
So tried to creat a module to achieve it.
I used a flag to deside which methods to be called on the object.
somehow it is not working.I realise after 2 days of struggle that
as  it is usuel , I am blind to my faults.
I tested all the metheds except main() in idle interactively,found them
working.
So there is a bug in the main(), kan anyone point it out to me?




#! usr/bin/env python

import ast,random,os,zlib,string
key=5
class Cripto(object):
def __init__(self,afile):
self.afile=afile
def __digi(self,astring):
y=[]
for x in astring:
y.append(ord(x))
y=str(y)

return y
def __undigi(self,astring):

alist=ast.literal_eval(astring)
y=[]
for x in alist:
y.append(chr(x))
astring=''.join(y)
return astring
def __gen_string(self):
s=''
 nl=random.sample(string.ascii_letters,key)
 for x in nl:s+=x
 return s

def __lengthen(self,astring):
 s=list(astring)
  ns=''
  for x in s:
  ns+=x
  ns+=gen_string()
  return ns
def __shorten(self,astring):

 s=list(astring)
  ns=''
  for x in range(0,len(s),key+1):
  ns+=s[x]
  return ns
def __compress(self,astring):
astring=zlib.compress(astring)
return astring
def __decompress(self,astring):
astring=zlib.decompress(astring)
return astring
def main(self):
sorce=open(self.afile,'r')
data=(sorce.readlines())
dest=open ((os.path.split(self.afile)[0]+os.sep+'temp'),'w')
if data[:1]=='flag1\n':
ns='flag0\n'
data=data[1:]
for line in data:
   nl=__compress((__digi(__lengthen(line.strip()+'\n'
   ns+=nl
dest.write(ns)
elif data[:1]=='flag0\n':
ns='flag1\n'
data=data[1:]
for line in data:
nl=__decompress((__undigi(__shorten(line.strip()+'\n'
ns+=nl
dest.write(ns)

sorce.close()
dest.close()

os.remove(self.afile)
os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile)


#
a=Cripto('C:/pp.txt')
a.main()


<\code>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flag to call methods on objects?

2009-07-30 Thread prasad rao
On 7/30/09, Rich Lovely  wrote:
>
> 2009/7/30 prasad rao prasadarao...@gmail.com:




>I'm sure there are modules available for PGP that are either part of
> >the stdlib, or available from a quick google.  PGP (or GPG) encryopts
>

  I never know there is an encryption module in stdlib.
What is its name?

Prasad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flag to call methods on objects?

2009-07-30 Thread Wayne
On Thu, Jul 30, 2009 at 8:49 AM, prasad rao  wrote:

>
>
> On 7/30/09, Rich Lovely  wrote:
>>
>> 2009/7/30 prasad rao prasadarao...@gmail.com:
>
>
>
>
> >I'm sure there are modules available for PGP that are either part of
>> >the stdlib, or available from a quick google.  PGP (or GPG) encryopts
>>
>
>   I never know there is an encryption module in stdlib.
> What is its name?
>

If you're only partially concerned (i.e. don't care about 'real' encryption)
you can use some of the string library encryptions.

def test_encod(mystr):
 mystr = str(mystr)
 print "%s zip encoded: %s" % (mystr, mystr.encode('zip'))
 print "%s rot13 encoded: %s" % (mystr, mystr.encode('rot13'))
 print "%s hex encoded: %s" % (mystr, mystr.encode('hex'))
 print "%s Base 64 encoded: %s" % (mystr, mystr.encode('base64'))


In [41]: test_encode("The quick brown fox jumps over the lazy dogs")
The quick brown fox jumps over the lazy dogs zip encoded: xœ

ÉHU(,ÍLÎVH*Ê/ÏSH˯PÈ*Í-(VÈ/K-R(Jç$VU*¤ä§l)M
The quick brown fox jumps over the lazy dogs rot13 encoded: Gur dhvpx oebja
sbk whzcf bire gur ynml qbtf
The quick brown fox jumps over the lazy dogs hex encoded:
54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f6773
The quick brown fox jumps over the lazy dogs Base 64 encoded:
VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZ3M=

So you could easily convert with encode and then reconvert with decode.

Another option would be a simple XOR of your data ( from here:
http://www.evanfosmark.com/2008/06/xor-encryption-with-python/ )

from itertools import izip, cycle

def xor_crypt_string(data, key):
return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))

On the page provided someone also gave their code that can encrypt files.

Of course any of these methods presume you're just trying to keep the casual
snoop from getting access to your data. Anyone with time/inclination/tools
can go ahead and break most encryptions.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Issues with regex escaping on \{

2009-07-30 Thread gpo

Thanks!  The ? got rid of the greediness! 


vince spicer wrote:
> 
> On Wed, Jul 29, 2009 at 11:35 AM, gpo  wrote:
> 
> 
> your grouping (.+) appears to be greedy, you can make it non-greedy with a
> question mark
> 
> EX:
> 
> pUserID=re.compile('UserID:\s+{(.+?)}',re.I)
> 
> Vince
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: 
http://www.nabble.com/Issues-with-regex-escaping-on-%5C%7B-tp24724060p24726284.html
Sent from the Python - tutor mailing list archive at Nabble.com.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Companion CD for Python Book

2009-07-30 Thread Randy Seys
Hi,

I recently purchased a used book with the title Python Programming for the 
Absolute Beginner, Second Edition, by Michael Dawson.  The book is supposed 
include a companion CD, but the CD is broken.  I've already contacted the 
publisher for a replacement, but they were not able to help me.  If someone has 
this CD, would it be possible for me to receive a zip file of the CD contents?  
Any other ideas on how I could get a copy of this CD?

Thank you for any help you can pass my way.

Regards,

Randy S
Mankato, MN___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flag to call methods on objects?

2009-07-30 Thread Dave Angel

prasad rao wrote:

hello
I wanted to prevent other users of my computers to read my files.
So tried to creat a module to achieve it.
I used a flag to deside which methods to be called on the object.
somehow it is not working.I realise after 2 days of struggle that
as  it is usuel , I am blind to my faults.
I tested all the metheds except main() in idle interactively,found them
working.
So there is a bug in the main(), kan anyone point it out to me?




#! usr/bin/env python

import ast,random,os,zlib,string
key=5
class Cripto(object):
def __init__(self,afile):
self.afile=afile
def __digi(self,astring):
y=[]
for x in astring:
y.append(ord(x))
y=str(y)

return y
def __undigi(self,astring):

alist=ast.literal_eval(astring)
y=[]
for x in alist:
y.append(chr(x))
astring=''.join(y)
return astring
def __gen_string(self):
s=''
 nl=random.sample(string.ascii_letters,key)
 for x in nl:s+=x
 return s

def __lengthen(self,astring):
 s=list(astring)
  ns=''
  for x in s:
  ns+=x
  ns+=gen_string()
  return ns
def __shorten(self,astring):

 s=list(astring)
  ns=''
  for x in range(0,len(s),key+1):
  ns+=s[x]
  return ns
def __compress(self,astring):
astring=zlib.compress(astring)
return astring
def __decompress(self,astring):
astring=zlib.decompress(astring)
return astring
def main(self):
sorce=open(self.afile,'r')
data=(sorce.readlines())
dest=open ((os.path.split(self.afile)[0]+os.sep+'temp'),'w')
if data[:1]=='flag1\n':
ns='flag0\n'
data=data[1:]
for line in data:
   nl=__compress((__digi(__lengthen(line.strip()+'\n'
   ns+=nl
dest.write(ns)
elif data[:1]=='flag0\n':
ns='flag1\n'
data=data[1:]
for line in data:
nl=__decompress((__undigi(__shorten(line.strip()+'\n'
ns+=nl
dest.write(ns)

sorce.close()
dest.close()

os.remove(self.afile)
os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile)


#
a=Cripto('C:/pp.txt')
a.main()


<\code>

  
First problem is the indentation.  It won't compile as it is.  I'll 
assume that was somehow a pasting error.


Next problem is where you're comparing for 'flag1'Your line   if 
data[:1] == 'flag1\n' is comparing a list on the left side to a 
string on the right.  If it were me, I'd replace that test, and the 
similar one below it, with

   if data[0].rstrip()=='flag1':


The reason for the rstrip() is to make it easier for a test harness, 
where it may be a pain to get the newlines on each line.  Also, it's 
harder to spot a whitespace error.


Next problem/question is whether this is only going to be used for files 
that happen to begin with a line flag1.   If so, it should be 
documented as part of the code, along with all the other missing 
documentation/docstrings.



That's as far as I went;  I did not test the actual encoding logic  But 
some free advice for next time:When you ask a question, please 
supply a compilable program, and either test data, or enough description 
that we can build such.  And please tell us what the symptom is.


"it is not working."  is not very descriptive.


DaveA
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flag to call methods on objects?

2009-07-30 Thread prasad rao
On 7/30/09, Dave Angel  wrote:
>
> prasad rao wrote:
>
>> hello
>>
>> >"it is not working."  is not very descriptive.
>>
>>
>> DaveA
>>
>Hello!  Sorry, I forgot to mention  the problem.
It simply wipes clean the file,resulting in empty file.
Yes .I should compare with a string.Hope I will get it
right with that correction.


Thank you Wayne.
I never know string module can be used for encryption.
I will try all those methods(shown by you) in my module.

Thank you all

Prasad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flag to call methods on objects?

2009-07-30 Thread Dave Angel

prasad rao wrote:

On 7/30/09, Dave Angel  wrote:
  

prasad rao wrote:



hello

  

"it is not working."  is not very descriptive.


DaveA

  

   Hello!  Sorry, I forgot to mention  the problem.


It simply wipes clean the file,resulting in empty file.
Yes .I should compare with a string.Hope I will get it
right with that correction.

  
That's due to another bug in the main() method.  You have an if, elif, 
but no else clause when you're checking the first line.  So if you have 
a file that does *not* begin with the magic string, it'll get 
truncated.  Probably not part of your spec.


DaveA
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flag to call methods on objects?

2009-07-30 Thread Steve Willoughby
On Thu, Jul 30, 2009 at 09:11:42AM -0500, Wayne wrote:
> If you're only partially concerned (i.e. don't care about 'real' encryption)
> you can use some of the string library encryptions.

Please don't get used to calling these "encryption".  They have nothing
at all to do with encrypting data.  (Well, ROT13 does, I suppose, but
not seriously).  They are for "encoding" which is simply representing
data in a different FORMAT. They do not encrypt data.  Yes, people have
actually tried "encrypting" passwords sent between browsers and web apps
using base64 and suchlike.  BIG mistake.  

You do say that somewhat, but I think using the word "encryption" or 
implying that these represent a casual level of encryption, is just leading
to trouble.  These are things a lot of people can decode in their heads.

Libraries like the Python Cryptography Toolkit provide real encryption
very easily if you need encryption.

> Of course any of these methods presume you're just trying to keep the casual
> snoop from getting access to your data. Anyone with time/inclination/tools
> can go ahead and break most encryptions.

In one line of code, you can convert a string to base64 or hex
and get a string that would take anyone caring to about 2 seconds to
reverse, using tools as simple as most text editors, python itself,
or for that matter some network monitoring programs which might pick up
that data in flight would just automatically decode that for you.

However, in only another line or so of code, you can encrypt
your data using AES or Blowfish or whatever, which would require
highly specialized tools, extremely expensive equipment, and if you
were not either a major government, independently wealthy and very
motivated to get that data, it's not going to be broken.


-- 
Steve Willoughby|  Using billion-dollar satellites
st...@alchemy.com   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Currency conversion module in python

2009-07-30 Thread Che M

Did you actually look at what happens when you click that
link?  (i.e. where you are brought to?).  

Because upon viewing this I achieved enlightenment!  :D


Date: Thu, 30 Jul 2009 10:02:39 +0200
From: zebr...@gmail.com
To: amit.pureene...@gmail.com
CC: tutor@python.org
Subject: Re: [Tutor] Currency conversion module in python

Hi Amit, this might be what you want..hopefully with a dollop of humor :)

http://lmgtfy.com/?q=currency+conversion+module+in+python&l=1


Cheers

On Thu, Jul 30, 2009 at 12:45 AM, Amit Sethi  wrote:

Hi , Does anybody know of any currency conversion module in python



--

A-M-I-T S|S

___

Tutor maillist  -  Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor



-- 
Lloyd Dube

_
Windows Live™ Hotmail®: Celebrate the moment with your favorite sports pics. 
Check it out.
http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_photos_072009&cat=sports___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread Marv Boyes
Hello, all. This is probably embarrassingly basic, but I haven't been 
able to find something that works.


I'm working on a script that needs to manipulate a list (not 'list' in 
the Python sense) of URLs returned in a server response. Right now, I'm 
stripping the XML tags from that response and assigning the resulting 
list of URLs to a variable so I can print it in the terminal. So when I 
do, say, 'print urls' I get something like this:


http://server.com/thing1
http://server.com/thing2
http://server.com/thing3

And so on. What I would _like_ to do is assign each line of that list to 
a separate variable, so that I can format my output to be more explicit; 
something like this:


Link to Thing1: http://server.com/thing1
Link to Thing2: http://server.com/thing2

And so on. I know this should be extremely easy, but I appear to be 
having some manner of mental block. Any and all guidance would be 
greatly appreciated; many thanks in advance.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread vince spicer
On Thu, Jul 30, 2009 at 1:19 PM, Marv Boyes  wrote:

> Hello, all. This is probably embarrassingly basic, but I haven't been able
> to find something that works.
>
> I'm working on a script that needs to manipulate a list (not 'list' in the
> Python sense) of URLs returned in a server response. Right now, I'm
> stripping the XML tags from that response and assigning the resulting list
> of URLs to a variable so I can print it in the terminal. So when I do, say,
> 'print urls' I get something like this:
>
>http://server.com/thing1
>http://server.com/thing2
>http://server.com/thing3
>
> And so on. What I would _like_ to do is assign each line of that list to a
> separate variable, so that I can format my output to be more explicit;
> something like this:
>
>Link to Thing1: http://server.com/thing1
>Link to Thing2: http://server.com/thing2
>
> And so on. I know this should be extremely easy, but I appear to be having
> some manner of mental block. Any and all guidance would be greatly
> appreciated; many thanks in advance.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Hello,

you could use a dictionary to assign a key value and a descrption, but
without seeing some data this is very rough

data = {}
for line in response:
key, value = response.split(",")  # line is "myname, http://blah.com";
data[key] = value

#then later
for key, value in data.items():
print "Link To %s : %s" % key, value
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread Kent Johnson
On Thu, Jul 30, 2009 at 3:19 PM, Marv Boyes wrote:
> Hello, all. This is probably embarrassingly basic, but I haven't been able
> to find something that works.
>
> I'm working on a script that needs to manipulate a list (not 'list' in the
> Python sense) of URLs returned in a server response. Right now, I'm
> stripping the XML tags from that response and assigning the resulting list
> of URLs to a variable so I can print it in the terminal. So when I do, say,
> 'print urls' I get something like this:
>
>        http://server.com/thing1
>        http://server.com/thing2
>        http://server.com/thing3
>
> And so on. What I would _like_ to do is assign each line of that list to a
> separate variable, so that I can format my output to be more explicit;
> something like this:
>
>        Link to Thing1: http://server.com/thing1
>        Link to Thing2: http://server.com/thing2

It looks like your "list" of URLs is a string containing one URL per
line. If you put it in an actual list, you can process it more
flexibly. Something like

urlList = urls.splitlines()
for i, url in enumerate(urlList):
  print "Link to Thing%s: %s" % (i, url)

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread Marv Boyes
I'm very sorry; I should have been more explicit in what it is I'm 
working with.


The response from the server consists of a pair of hashes and a list of 
URLs for doing different things with the file the hashes represent. So 
the full response is like this:


file_hash
delete_hash
http://server.com/file_hash.ext
http://server.com/file_hashA.ext
http://server.com/file_hashB.ext
http://server.com/file_hashC.ext
http://server.com/delete/deletehash

I'm hoping to assign each line of that response to a separate variable 
so I can format the output on a case-by-case basis, e.g.:


direct_link = 
print "Direct link to file: %s' % direct_link

-or-

delete_file = 
print "Delete the file: %s' % delete_file

I've got seven lines worth of server response, their order is 
significant, and I need to be able to present each value in an arbitrary 
way. I won't necessarily be presenting these values to the user in the 
same order they come in the server response. Some of the values I'll 
need to use elsewhere in the script to do other things, but it won't be 
necessary to present those values to the user.


I'm not sure I'm even making sense to myself.


Kent Johnson wrote:

On Thu, Jul 30, 2009 at 3:19 PM, Marv Boyes wrote:

Hello, all. This is probably embarrassingly basic, but I haven't been able
to find something that works.

I'm working on a script that needs to manipulate a list (not 'list' in the
Python sense) of URLs returned in a server response. Right now, I'm
stripping the XML tags from that response and assigning the resulting list
of URLs to a variable so I can print it in the terminal. So when I do, say,
'print urls' I get something like this:

   http://server.com/thing1
   http://server.com/thing2
   http://server.com/thing3

And so on. What I would _like_ to do is assign each line of that list to a
separate variable, so that I can format my output to be more explicit;
something like this:

   Link to Thing1: http://server.com/thing1
   Link to Thing2: http://server.com/thing2


It looks like your "list" of URLs is a string containing one URL per
line. If you put it in an actual list, you can process it more
flexibly. Something like

urlList = urls.splitlines()
for i, url in enumerate(urlList):
  print "Link to Thing%s: %s" % (i, url)

Kent



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Currency conversion module in python

2009-07-30 Thread wesley chun
On Thu, Jul 30, 2009 at 11:18 AM, Che M wrote:
> Did you actually look at what happens when you click that
> link?  (i.e. where you are brought to?).
>
> Because upon viewing this I achieved enlightenment!  :D


lucky you... i achieved recursion. :-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread Jeremy Hoon
On Thu, Jul 30, 2009 at 4:26 PM, Marv Boyes wrote:
> I'm very sorry; I should have been more explicit in what it is I'm working
> with.
>
> The response from the server consists of a pair of hashes and a list of URLs
> for doing different things with the file the hashes represent. So the full
> response is like this:
>
>        file_hash
>        delete_hash
>        http://server.com/file_hash.ext
>        http://server.com/file_hashA.ext
>        http://server.com/file_hashB.ext
>        http://server.com/file_hashC.ext
>        http://server.com/delete/deletehash
>
> I'm hoping to assign each line of that response to a separate variable so I
> can format the output on a case-by-case basis, e.g.:
>
>        direct_link = 
>        print "Direct link to file: %s' % direct_link
>
>        -or-
>
>        delete_file = 
>        print "Delete the file: %s' % delete_file
>
> I've got seven lines worth of server response, their order is significant,
> and I need to be able to present each value in an arbitrary way. I won't
> necessarily be presenting these values to the user in the same order they
> come in the server response. Some of the values I'll need to use elsewhere
> in the script to do other things, but it won't be necessary to present those
> values to the user.
>
> I'm not sure I'm even making sense to myself.
>
>
> Kent Johnson wrote:
>>
>> On Thu, Jul 30, 2009 at 3:19 PM, Marv Boyes wrote:
>>>
>>> Hello, all. This is probably embarrassingly basic, but I haven't been
>>> able
>>> to find something that works.
>>>
>>> I'm working on a script that needs to manipulate a list (not 'list' in
>>> the
>>> Python sense) of URLs returned in a server response. Right now, I'm
>>> stripping the XML tags from that response and assigning the resulting
>>> list
>>> of URLs to a variable so I can print it in the terminal. So when I do,
>>> say,
>>> 'print urls' I get something like this:
>>>
>>>       http://server.com/thing1
>>>       http://server.com/thing2
>>>       http://server.com/thing3
>>>
>>> And so on. What I would _like_ to do is assign each line of that list to
>>> a
>>> separate variable, so that I can format my output to be more explicit;
>>> something like this:
>>>
>>>       Link to Thing1: http://server.com/thing1
>>>       Link to Thing2: http://server.com/thing2
>>
>> It looks like your "list" of URLs is a string containing one URL per
>> line. If you put it in an actual list, you can process it more
>> flexibly. Something like
>>
>> urlList = urls.splitlines()
>> for i, url in enumerate(urlList):
>>  print "Link to Thing%s: %s" % (i, url)
>>
>> Kent
>>
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Hi Marv,

While I'm not convinced hard-coding variables to list items is the
best solution here, you could achieve it with tuple unpacking:

urllist = urls.split()

# urllist should have three items in it, otherwise an exception is raised.
# You will need to adapt this to the length of your list of urls.
link_one,link_two,link_three = urllist

print "the first link:", link_one
print "the second link:", link_two

Best,
Jeremy
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread Dave Angel

Marv Boyes wrote:
Hello, 
all. This is probably embarrassingly basic, but I haven't been able to 
find something that works.


I'm working on a script that needs to manipulate a list (not 'list' in 
the Python sense) of URLs returned in a server response. Right now, 
I'm stripping the XML tags from that response and assigning the 
resulting list of URLs to a variable so I can print it in the 
terminal. So when I do, say, 'print urls' I get something like this:


http://server.com/thing1
http://server.com/thing2
http://server.com/thing3

And so on. What I would _like_ to do is assign each line of that list 
to a separate variable, so that I can format my output to be more 
explicit; something like this:


Link to Thing1: http://server.com/thing1
Link to Thing2: http://server.com/thing2

And so on. I know this should be extremely easy, but I appear to be 
having some manner of mental block. Any and all guidance would be 
greatly appreciated; many thanks in advance.



Usually, when people say they want to assign items from a list to 
separate variables, it's because they don't understand lists.  But I'll 
give you several (untested) fragments, and see if one of them comes 
close to what you really want.



Assuming URLs is your current list, and that it has exactly 3 items in it.

here, there, everwhere = URLs
 will give you those three variables, each assigned to one of the 
URL strings


print "Link to Thing1", URLs[0]
print "Link to Thing2", URLs[1]
print "Link to Thing3", URLs[2]
lets you print them out individually, without wasting any separate 
assignments, or giving them explicit names


for index, item in enumerate(URLs):
 print "Link to Thing%s" % index,  item

 will print out your original request, and even work if you change 
the list to have 4 or 5 items


HTH

DaveA


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Troubles with the mailing list.

2009-07-30 Thread Mac Ryan
Hi all,

having seen a few people in the past days sending "trial messages" on
the list I figured it out that I must not be the only one to experience
problems with it.

I even set up the "notification" feature that sends you an
acknowledgement message when your mail is received from the server, but
as a matter of facts, I did not even got that back for my previous
message.

I was just wondering if the list-owners are aware of the problem or
not, and if anything can be done to fix it.

Mac.

PS: I also notice that some messages (quoted in replies) are not
reaching my mbox or are reaching it after I got a reply to them. This
could be a problem on my side though. Anybody experiencing similar
issues? (I am using gmail, btw).

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problems understanding control flow

2009-07-30 Thread Eduardo Vieira
Hello, list.
I can't understand why the print statement is not printed with the
operator '==', but is printed when using 'in'.
Here's the code:
#===
import csv

bv = """NAME,BVADDRTELNO1,BVADDREMAIL
Company1, 1234567788, t...@that.com
CompanyA, 1231234455, t...@this.com
CompanyC, 101101, n...@this.com
CompanyD, 22, o...@olde.com

"""
site = """Company,Email,Phone
"Company3","noth...@nada.com","123456"
"CompanyD","o...@olde.com","22"
"Company1","t...@that.com","1234567788"
"""

bv = bv.upper() # This is just to make the data more homogeneous and
detect duplicates more easily


site = site.upper()


bvreader = csv.DictReader(bv.splitlines())

sitelist = csv.DictReader(site.splitlines())

bvreaderone = list(bvreader)

# this does not work:
for row in sitelist:
   for line in bvreaderone:
   if row['EMAIL'] == line['BVADDREMAIL']:
   print line['NAME'], row['COMPANY']

# but this does work:
for row in sitelist:
   for line in bvreaderone:
   if row['EMAIL'] in line['BVADDREMAIL']:
   print line['NAME'], row['COMPANY']

#==

Regards,

Eduardo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Companion CD for Python Book

2009-07-30 Thread Tommie
>Randy S wrote:

>Hi,

>I recently purchased a used book with the title >Python Programming for the
Absolute Beginner, >Second Edition, by Michael Dawson.  The book is
>supposed include a companion CD, but the CD is >broken.  I've already
contacted the publisher for a >replacement, but they were not able to help
me.  If >someone has this CD, would it be possible for me to >receive a zip
file of the CD contents?  Any other >ideas on how I could get a copy of this
CD?

>Thank you for any help you can pass my way.

>Regards,

>Randy S
>Mankato, MN


I recall reading in an Amazon review last week that someone had similar
trouble with this title and was unable to get help from the publisher, but
the author was able to help after an email through his website.  You may
want to look that avenue up.--
Tommie

"Any fool can criticize, condemn and complain - and most fools do." --Dale
Carnegie
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems understanding control flow

2009-07-30 Thread Sander Sweers
2009/7/30 Eduardo Vieira :

With == you are testing if the 2 values are exactly the same. So 'one'
== 'one' will return True but 'one; == 'one two' will return False.

With in you test if the value is part of a another value. So using the
same value as above 'one' in 'one' will return True but 'one' in 'one
two' will also return True as 'one' is part of the second string.

The same logic applies to lists and dicts. 'one' == ['one', 'two']
will return False as the the 2 values are not exactly the same but
'one' in ['one', 'two'] will return True.

> # this does not work:
> for row in sitelist:
>   for line in bvreaderone:

If you are getting unexpected results add in print statements to see
what is the data that you are working with. I would add the below 2
print statements to see what you are now actually comparing. Same
applies to the other working example.
:
print 'Value row['EMAIL'] is: %s' % row['EMAIL']
print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL']

>       if row['EMAIL'] == line['BVADDREMAIL']:

Here you are testing if the value of row['EMAIL'] is exactly the same
as line['BVADDREMAIL']: which is not the case so the test returns
False and the below print statement is not executed.

>           print line['NAME'], row['COMPANY']
>
> # but this does work:
> for row in sitelist:
>   for line in bvreaderone:
>       if row['EMAIL'] in line['BVADDREMAIL']:

Here you test if the value row['E_MAIL'] is part of
line['BVADDREMAIL']:which is True.

>           print line['NAME'], row['COMPANY']

Someone did a way better job writing this down some time a go but
can't find the post online. I hope you see now what the difference is
between the 2.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems understanding control flow

2009-07-30 Thread Eduardo Vieira
On Thu, Jul 30, 2009 at 4:49 PM, Sander Sweers wrote:
> 2009/7/30 Eduardo Vieira :
>
> With == you are testing if the 2 values are exactly the same. So 'one'
> == 'one' will return True but 'one; == 'one two' will return False.
>
> With in you test if the value is part of a another value. So using the
> same value as above 'one' in 'one' will return True but 'one' in 'one
> two' will also return True as 'one' is part of the second string.
>
> The same logic applies to lists and dicts. 'one' == ['one', 'two']
> will return False as the the 2 values are not exactly the same but
> 'one' in ['one', 'two'] will return True.
>
>> # this does not work:
>> for row in sitelist:
>>   for line in bvreaderone:
>
> If you are getting unexpected results add in print statements to see
> what is the data that you are working with. I would add the below 2
> print statements to see what you are now actually comparing. Same
> applies to the other working example.
> :
>    print 'Value row['EMAIL'] is: %s' % row['EMAIL']
>    print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL']
>
>>       if row['EMAIL'] == line['BVADDREMAIL']:
>
> Here you are testing if the value of row['EMAIL'] is exactly the same
> as line['BVADDREMAIL']: which is not the case so the test returns
> False and the below print statement is not executed.
>
>>           print line['NAME'], row['COMPANY']
>>
>> # but this does work:
>> for row in sitelist:
>>   for line in bvreaderone:
>>       if row['EMAIL'] in line['BVADDREMAIL']:
>
> Here you test if the value row['E_MAIL'] is part of
> line['BVADDREMAIL']:which is True.
>
>>           print line['NAME'], row['COMPANY']
>
> Someone did a way better job writing this down some time a go but
> can't find the post online. I hope you see now what the difference is
> between the 2.
Thanks for pointing out this, Sander. Yes, a print statement revealed
the right after commas... In this case I should enable the option from
the csv module to ignore such white spaces.

Eduardo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems understanding control flow

2009-07-30 Thread Eduardo Vieira
On Thu, Jul 30, 2009 at 5:56 PM, Eduardo Vieira wrote:
> On Thu, Jul 30, 2009 at 4:49 PM, Sander Sweers wrote:
>> 2009/7/30 Eduardo Vieira :
>>
>> With == you are testing if the 2 values are exactly the same. So 'one'
>> == 'one' will return True but 'one; == 'one two' will return False.
>>
>> With in you test if the value is part of a another value. So using the
>> same value as above 'one' in 'one' will return True but 'one' in 'one
>> two' will also return True as 'one' is part of the second string.
>>
>> The same logic applies to lists and dicts. 'one' == ['one', 'two']
>> will return False as the the 2 values are not exactly the same but
>> 'one' in ['one', 'two'] will return True.
>>
>>> # this does not work:
>>> for row in sitelist:
>>>   for line in bvreaderone:
>>
>> If you are getting unexpected results add in print statements to see
>> what is the data that you are working with. I would add the below 2
>> print statements to see what you are now actually comparing. Same
>> applies to the other working example.
>> :
>>    print 'Value row['EMAIL'] is: %s' % row['EMAIL']
>>    print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL']
>>
>>>       if row['EMAIL'] == line['BVADDREMAIL']:
>>
>> Here you are testing if the value of row['EMAIL'] is exactly the same
>> as line['BVADDREMAIL']: which is not the case so the test returns
>> False and the below print statement is not executed.
>>
>>>           print line['NAME'], row['COMPANY']
>>>
>>> # but this does work:
>>> for row in sitelist:
>>>   for line in bvreaderone:
>>>       if row['EMAIL'] in line['BVADDREMAIL']:
>>
>> Here you test if the value row['E_MAIL'] is part of
>> line['BVADDREMAIL']:which is True.
>>
>>>           print line['NAME'], row['COMPANY']
>>
>> Someone did a way better job writing this down some time a go but
>> can't find the post online. I hope you see now what the difference is
>> between the 2.
> Thanks for pointing out this, Sander. Yes, a print statement revealed
> the right after commas... In this case I should enable the option from
> the csv module to ignore such white spaces.
>
> Eduardo
>
I meant  a print statement revealed the extra space right after commas...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread Dave Angel

Marv Boyes wrote:
I'm very 
sorry; I should have been more explicit in what it is I'm working with.


The response from the server consists of a pair of hashes and a list 
of URLs for doing different things with the file the hashes represent. 
So the full response is like this:


file_hash
delete_hash
http://server.com/file_hash.ext
http://server.com/file_hashA.ext
http://server.com/file_hashB.ext
http://server.com/file_hashC.ext
http://server.com/delete/deletehash

I'm hoping to assign each line of that response to a separate variable 
so I can format the output on a case-by-case basis, e.g.:


direct_link = 
print "Direct link to file: %s' % direct_link

-or-


delete_file = 
print "Delete the file: %s' % delete_file

I've got seven lines worth of server response, their order is 
significant, and I need to be able to present each value in an 
arbitrary way. I won't necessarily be presenting these values to the 
user in the same order they come in the server response. Some of the 
values I'll need to use elsewhere in the script to do other things, 
but it won't be necessary to present those values to the user.


I'm not sure I'm even making sense to myself.


Assuming the server response is in a single string, which consists of 7 
strings separated by newlines.


response = server_getdata()
responseList = response.splitlines()
file_hash, delete_hash, direct_link, other_link, other_link3, 
other_link4, delete_file = responseList


DaveA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] flag to call methods on objects?

2009-07-30 Thread prasad rao
hello
 I removed the bugs.But still getting error report.


>>import mcript

Traceback (most recent call last):
  File "", line 1, in 
import mcript
  File "C:\Python26\mcript.py", line 78, in 
a.main()
  File "C:\Python26\mcript.py", line 58, in main
nl=__compress(__digi(__lengthen(line.strip(+'\n'
NameError: global name '_Cripto__compress' is not defined

There is no string  '_Cripto__compress'  any whare in the script.

So I dont know what corrections Ineed to make in the script.

I am giving my code below again again .



#! usr/bin/env python

import ast,random,os,zlib,string
key=5
class Cripto(object):
def __init__(self,afile):
self.afile=afile
def __digi(self,astring):
y=[]
for x in astring:
y.append(ord(x))
y=str(y)

return y
def __undigi(self,astring):

alist=ast.literal_eval(astring)
y=[]
for x in alist:
y.append(chr(x))
astring=''.join(y)
return astring
def __gen_string(self):
s=''
nl=random.sample(string.ascii_letters,key)
for x in nl:s+=x
return s

def __lengthen(self,astring):
 s=list(astring)
 ns=''
 for x in s:
 ns+=x
 ns+=gen_string()
 return ns
def __shorten(self,astring):

 s=list(astring)
 ns=''
 for x in range(0,len(s),key+1):
ns+=s[x]
return ns
def __compress(self,astring):
astring=zlib.compress(astring)
return astring
def __decompress(self,astring):
astring=zlib.decompress(astring)
return astring
def main(self):
sorce=open(self.afile,'r')
data=(sorce.readlines())
dest=open((os.path.split(self.afile)[0]+os.sep+'temp'),'w')
if (data[0]).strip()=='flag1':

ns='flag0\n'
data=data[1:]
for line in data:
   nl= __compress(__digi(__lengthen(line.strip(+'\n'
   ns+=nl
dest.write(ns)
elif data[0].strip()=='flag0':
ns='flag1\n'
data=data[1:]
for line in data:
nl= __shorten((__undigi(__decompress(line.strip()+'\n'
ns+=nl
dest.write(ns)
else:prind 'File does not begin with the flag'

sorce.close()
dest.close()

os.remove(self.afile)
os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile)


#
a=Cripto('C:/pp.txt')
a.main()

<\code>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flag to call methods on objects?

2009-07-30 Thread Wayne
On Thu, Jul 30, 2009 at 11:29 PM, prasad rao wrote:

> hello
>  I removed the bugs.But still getting error report.
>
>
> >>import mcript
>
> Traceback (most recent call last):
>   File "", line 1, in 
> import mcript
>   File "C:\Python26\mcript.py", line 78, in 
> a.main()
>   File "C:\Python26\mcript.py", line 58, in main
>
That line tells you where the problem is

> nl=__compress(__digi(__lengthen(line.strip(+'\n'
>
That's the code that produced the error

> NameError: global name '_Cripto__compress' is not defined
>
You're trying to call a method __compress which doesn't exist.
self.__compress exists, but __compress doesn't. HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor