Re: [Tutor] Formatting text file with python

2018-02-07 Thread Alan Gauld via Tutor
On 06/02/18 21:07, Hüseyin Ertuğrul wrote:

> "hMailServer SpamProtection rejected RCPT (Sender: 
> valeria0...@mikelsonconstruction.com, IP:187.62.63.218, Reason: Rejected by 
> Spamhaus.)"
> "hMailServer SpamProtection rejected RCPT (Sender: veronika07...@etb.net.co, 
> IP:190.25.189.74, Reason: Rejected by SpamCop.)"
> "hMailServer SpamProtection rejected RCPT (Sender: 
> sofia...@pembroketownhouse.ie, IP:103.247.48.95, Reason: Rejected by 
> Spamhaus.)"
> 
> Traceback (most recent call last):
>   File "C:/Depo/Python/prj1/analiz.py", line 17, in 
> prnt(deger)
>   File "C:/Depo/Python/prj1/analiz.py", line 7, in prnt
> iplist = list_line[1]
> IndexError: list index out of range)

So you have a line with no commas in it. Have you checked
the line that causes the error - presumably right after
the last one that printed correctly.

> ---
> My code is below;
> def prnt(L1):
> 
> L1 = L1[:-1]
> 
> list_line = L1.split(",")

You are splitting by comma but I notice the IP addresses
all start with IP: so it might be easier/more reliable
to split by 'IP:' in case there are other messages with
commas but no IP addresses in them?

But even so you still need to either check the result
length or use a try/except IndexError to deal with malformed
lines.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Formatting text file with python

2018-02-07 Thread Hüseyin Ertuğrul
Hello friends,
I want to format the log (text) file my email's server.
The text file (named s1.txt) contains the following information, text file has 
about 3000 lines.

"hMailServer SpamProtection rejected RCPT (Sender: 
valeria0...@mikelsonconstruction.com, IP:187.62.63.218, Reason: Rejected by 
Spamhaus.)"
"hMailServer SpamProtection rejected RCPT (Sender: veronika07...@etb.net.co, 
IP:190.25.189.74, Reason: Rejected by SpamCop.)"
"hMailServer SpamProtection rejected RCPT (Sender: 
sofia...@pembroketownhouse.ie, IP:103.247.48.95, Reason: Rejected by Spamhaus.)"

I want to select ip addresses in text file and I want to delete duplicated 
records. Finally I want to write this data into a new file. What do you suggest 
me?

That codes returned me about 500 records and gives error ;

Traceback (most recent call last):
  File "C:/Depo/Python/prj1/analiz.py", line 17, in 
prnt(deger)
  File "C:/Depo/Python/prj1/analiz.py", line 7, in prnt
iplist = list_line[1]
IndexError: list index out of range)
---
My code is below;
def prnt(L1):

L1 = L1[:-1]

list_line = L1.split(",")
list0 = list_line[0]
iplist = list_line[1]
list2 = list_line[2]
print(iplist)


with open("s1.txt","r",) as file:

for deger in file:
prnt(deger)

#with open("iplistesi.txt","w") as file2:
#file2.write(i)


Best Regards.

Huseyin

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-28 Thread richard kappler
It occurred to me last night on the drive home that I should just run this
through an xml parser, then lo and behold this email was sitting in my
inbox when I got  home. Having tried that, my data is not as clean as I
first thought. It seems like a fairly simple fix, but durned if I can
figure out how to do it. One of the problems is data such as this (viewed
in the text editor, this is a log, not a stream):

1\x02 data data data \x03\x02 more data more data more data \x03\x02 even
more data even
2more data even more data\x03\x02 Mary had a little\x03\x02 lamb whose
fleece was white as
3snow\x03\x02

and so on. The 1,2,3 at the beginning of each above are just line numbers
in the text editor, they do not actually exist.

How do I read in the file, either in it's entirety or line by line, then
output the text with as \x02 the event data \x03 on each line, and when
python sees the \x03 it goes to a new line and continues to output?

On Tue, Dec 27, 2016 at 7:46 PM, David Rock  wrote:

> * Alan Gauld via Tutor  [2016-12-28 00:40]:
> > On 27/12/16 19:44, richard kappler wrote:
> > > Using python 2.7 - I have a large log file we recorded of streamed xml
> data
> > > that I now need to feed into another app for stress testing. The
> problem is
> > > the data comes in 2 formats.
> > >
> > > 1. each 'event' is a full set of xml data with opening and closing
> tags +
> > > x02 and x03 (stx and etx)
> > >
> > > 2. some events have all the xml data on one 'line' in the log, others
> are
> > > in typical nested xml format with lots of white space and multiple
> 'lines'
> > > in the log for each event, the first line of th e 'event' starting
> with an
> > > stx and the last line of the 'event' ending in an etx.
> >
> > It sounds as if an xml parser should work for both. After all
> > xml doesn't care about layout and whitespace etc.
> >
> > Which xml parser are you using - I assume you are not trying
> > to parse it manually using regex or string methjods - that's
> > rarely a good idea for xml.
>
> Yeah, since everything appears to be .., the "event" flags
> of [\x02] [\x03] may not even matter if you use an actual parser.
>
> --
> David Rock
> da...@graniteweb.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-27 Thread David Rock
* Alan Gauld via Tutor  [2016-12-28 00:40]:
> On 27/12/16 19:44, richard kappler wrote:
> > Using python 2.7 - I have a large log file we recorded of streamed xml data
> > that I now need to feed into another app for stress testing. The problem is
> > the data comes in 2 formats.
> > 
> > 1. each 'event' is a full set of xml data with opening and closing tags +
> > x02 and x03 (stx and etx)
> > 
> > 2. some events have all the xml data on one 'line' in the log, others are
> > in typical nested xml format with lots of white space and multiple 'lines'
> > in the log for each event, the first line of th e 'event' starting with an
> > stx and the last line of the 'event' ending in an etx.
> 
> It sounds as if an xml parser should work for both. After all
> xml doesn't care about layout and whitespace etc.
> 
> Which xml parser are you using - I assume you are not trying
> to parse it manually using regex or string methjods - that's
> rarely a good idea for xml.

Yeah, since everything appears to be .., the "event" flags
of [\x02] [\x03] may not even matter if you use an actual parser.

-- 
David Rock
da...@graniteweb.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-27 Thread Alan Gauld via Tutor
On 27/12/16 19:44, richard kappler wrote:
> Using python 2.7 - I have a large log file we recorded of streamed xml data
> that I now need to feed into another app for stress testing. The problem is
> the data comes in 2 formats.
> 
> 1. each 'event' is a full set of xml data with opening and closing tags +
> x02 and x03 (stx and etx)
> 
> 2. some events have all the xml data on one 'line' in the log, others are
> in typical nested xml format with lots of white space and multiple 'lines'
> in the log for each event, the first line of th e 'event' starting with an
> stx and the last line of the 'event' ending in an etx.

It sounds as if an xml parser should work for both. After all
xml doesn't care about layout and whitespace etc.

Which xml parser are you using - I assume you are not trying
to parse it manually using regex or string methjods - that's
rarely a good idea for xml.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-27 Thread David Rock
* richard kappler  [2016-12-27 16:05]:
> The input is consistent in that it all has stx at the beginning of each
> 'event.' I'm leaning towards regex. When you say:
> 
> " find stx, stuff lines until I see the next stx, then dump and continue"
> 
> Might I trouble you for an example of how you do that? I can find stx, I
> can find etx using something along the lines of :
> 
> a = [m.start() for m in re.finditer(r"", line)]
> 
> but then I get a little lost, mostly because I have some lines that have
> "data data [\x03][\x02] data" and then to the next line. More succinctly,
> the stx aren't always at the beginning of the line, etx not always at the
> end. No problem, I can find them, but then I'm guessing I would have to
> write to a buffer starting with stx, keep writing to the buffer until I get
> to etx, write the buffer to file (or send it over the socket, either way is
> fine) then continue on. The fact that 'events' span multiple lines is
> challenging me.

Well, that shows that in the context of line-based data, it is not
consistent.  That's the main issue.  If you knew that every event
started on a new line, then you could fairly easily:

if '\x02' in line:
output = line.strip()
while '\x02' not in line:
output = output + line.strip()

etc.

Unfortunately, we don't have that kind of line-based consistency.  You
are either going to have to treat it more like a binary stream of data,
triggering on stx and etx on a character-by-character basis, or you are
going to have to test for both stx and etx on each line and do different
things based on the combination you find.  Some possible options for
a single line appear to be:

[\x02]
[\x02] data
[\x02] data [\x03]
[\x02] data [\x03][\x02]
[\x03]
data [\x03]
data [\x03][\x02]
data [\x03][\x02] data

etc

That's assuming something really ugly like this couldn't happen on a
single line (but somehow I think it probably can):
data [\x03][\x02] data [\x03][\x02]

I think you are stuck reading as a character stream, rather than a
line-based text file due to the unstable nature of the input.

Another possibility (I suppose) would be to read per line and split on
the \x02 yourself (I'm assuming that's actually a single hex character).
That would artificially create "record" data that you could manipulate
and combine partial segments into complete xml records to parse.  Might
be faster, might not, probably would get complicated pretty quickly but
could be an option.

Without seeing actual data, it's tough to speculate what the best approach
would be.

-- 
David Rock
da...@graniteweb.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-27 Thread richard kappler
The input is consistent in that it all has stx at the beginning of each
'event.' I'm leaning towards regex. When you say:

" find stx, stuff lines until I see the next stx, then dump and continue"

Might I trouble you for an example of how you do that? I can find stx, I
can find etx using something along the lines of :

a = [m.start() for m in re.finditer(r"", line)]

but then I get a little lost, mostly because I have some lines that have
"data data [\x03][\x02] data" and then to the next line. More succinctly,
the stx aren't always at the beginning of the line, etx not always at the
end. No problem, I can find them, but then I'm guessing I would have to
write to a buffer starting with stx, keep writing to the buffer until I get
to etx, write the buffer to file (or send it over the socket, either way is
fine) then continue on. The fact that 'events' span multiple lines is
challenging me.

On Tue, Dec 27, 2016 at 3:55 PM, David Rock  wrote:

> * richard kappler  [2016-12-27 15:39]:
> > I was actually working somewhat in that direction while I waited. I had
> in
> > mind to use something along the lines of:
> >
> >
> > stx = '\x02'
> > etx = '\x03'
> > line1 = ""
> >
> > with open('original.log', 'r') as f1:
> >with open('new.log', 'w') as f2:
> > for line in f1:
> > if stx in line:
> > line1 = line1 + line
> > if not stx in line:
> > if not etx in line:
> > line1 = line1 + line
> > if etx in line:
> > line1 = line1 + line + '\n'
> > f2.write(line1)
> > line1 = ""
> >
> >
> > but that didn't work. It neither broke each line on etx (multiple events
> > with stx and etx on one line) nor did it concatenate the multi-line
> events.
>
> A big part of the challenge sounds like it's inconsistent data
> formatting.  You are going to have to identify some way to reliably
> check for the beginning/end of your data for it to work.  Do you know if
> you will always have \x02 at the start of a section of input, for example?
>
> The way I usually do log parsing in that case is use the stx as a flag
> to start doing other things (ie, if I find stx, stuff lines until I see
> the next stx, then dump and continue).  If you have intermediary data
> that is not between your stx and etx (comment lines, other data that you
> don't want), then it gets a lot harder.
>
> If you don't have at least a marginally consistent input, your only real
> option is probably going to be scanning by character and looking for the
> \x02 and \x03 to get a glob of data, then parse that glob with some kind
> of xml parser, since the data between those two is likely safe-ish.
>
> --
> David Rock
> da...@graniteweb.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-27 Thread David Rock
* richard kappler  [2016-12-27 15:39]:
> I was actually working somewhat in that direction while I waited. I had in
> mind to use something along the lines of:
> 
> 
> stx = '\x02'
> etx = '\x03'
> line1 = ""
> 
> with open('original.log', 'r') as f1:
>with open('new.log', 'w') as f2:
> for line in f1:
> if stx in line:
> line1 = line1 + line
> if not stx in line:
> if not etx in line:
> line1 = line1 + line
> if etx in line:
> line1 = line1 + line + '\n'
> f2.write(line1)
> line1 = ""
> 
> 
> but that didn't work. It neither broke each line on etx (multiple events
> with stx and etx on one line) nor did it concatenate the multi-line events.

A big part of the challenge sounds like it's inconsistent data
formatting.  You are going to have to identify some way to reliably
check for the beginning/end of your data for it to work.  Do you know if
you will always have \x02 at the start of a section of input, for example?  

The way I usually do log parsing in that case is use the stx as a flag
to start doing other things (ie, if I find stx, stuff lines until I see
the next stx, then dump and continue).  If you have intermediary data
that is not between your stx and etx (comment lines, other data that you
don't want), then it gets a lot harder.

If you don't have at least a marginally consistent input, your only real
option is probably going to be scanning by character and looking for the
\x02 and \x03 to get a glob of data, then parse that glob with some kind
of xml parser, since the data between those two is likely safe-ish.

-- 
David Rock
da...@graniteweb.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-27 Thread richard kappler
I was actually working somewhat in that direction while I waited. I had in
mind to use something along the lines of:


stx = '\x02'
etx = '\x03'
line1 = ""

with open('original.log', 'r') as f1:
   with open('new.log', 'w') as f2:
for line in f1:
if stx in line:
line1 = line1 + line
if not stx in line:
if not etx in line:
line1 = line1 + line
if etx in line:
line1 = line1 + line + '\n'
f2.write(line1)
line1 = ""


but that didn't work. It neither broke each line on etx (multiple events
with stx and etx on one line) nor did it concatenate the multi-line events.

On Tue, Dec 27, 2016 at 3:25 PM, David Rock  wrote:

> * richard kappler  [2016-12-27 14:44]:
> >
> > I have tried to feed this raw into our other app (Splunk) and the app
> reads
> > each line (gedit numbered line) as an event. I want everything in between
> > each stx and etx to be one event.
> >
> > I have tried:
> >
> > #
> > with open("original.log", 'r') as f1:
> > with open("new.log", 'a') as f2:
> > for line in f1:
> > line2 = line.replace("\n", "")
> > f2.write(line2)
> > ##
> >
> > Now this obviously doesn't work because, as stated above, each tag and
> > datum in the example above from lines 2 to 7 is on a different line, so
> > python is doing exactly as I tell it, it's stripping the \n and then
> > printing the line, but not concatenating everything between stx and etx
> on
> > one line, which is what I want it to do.
> >
> > What I'm trying to do is collapse the 'expanded lines' between stx and
> etx
> > to one line, but I just can't wrap my head around how to do it. Or to
> put,
> > and do, it another way, how do I read each line from the original file,
> but
> > write it to another file so that everything from stx to etx, including
> stx
> > and etx, are on one line in the file?
>
> Concatinate all your lines into a single output variable first, then
> write that to your log
>
> Pseudocode (ie, this won't run), but this should give you the idea
> (defining the parts to loop will be the challenge you will have to
> define for yourself).
>
> with open("original.log", 'r') as f1:
> with open("new.log", 'a') as f2:
> output = ""
> for line in f1:
> if between [x02] and [x03]:
> output =+ line.strip()
> else:
> f2.write(output)
> output = ""
>
> Basically, you need to loop over everything between your markers and put
> them in a single entry, then send that one entry all at once instead of
> piecemeal.
>
> I can come up with something a little more complete if you still need
> more help.
>
> --
> David Rock
> da...@graniteweb.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting xml (again)

2016-12-27 Thread David Rock
* richard kappler  [2016-12-27 14:44]:
> 
> I have tried to feed this raw into our other app (Splunk) and the app reads
> each line (gedit numbered line) as an event. I want everything in between
> each stx and etx to be one event.
> 
> I have tried:
> 
> #
> with open("original.log", 'r') as f1:
> with open("new.log", 'a') as f2:
> for line in f1:
> line2 = line.replace("\n", "")
> f2.write(line2)
> ##
> 
> Now this obviously doesn't work because, as stated above, each tag and
> datum in the example above from lines 2 to 7 is on a different line, so
> python is doing exactly as I tell it, it's stripping the \n and then
> printing the line, but not concatenating everything between stx and etx on
> one line, which is what I want it to do.
> 
> What I'm trying to do is collapse the 'expanded lines' between stx and etx
> to one line, but I just can't wrap my head around how to do it. Or to put,
> and do, it another way, how do I read each line from the original file, but
> write it to another file so that everything from stx to etx, including stx
> and etx, are on one line in the file?

Concatinate all your lines into a single output variable first, then
write that to your log

Pseudocode (ie, this won't run), but this should give you the idea
(defining the parts to loop will be the challenge you will have to
define for yourself).

with open("original.log", 'r') as f1:
with open("new.log", 'a') as f2:
output = ""
for line in f1:
if between [x02] and [x03]:
output =+ line.strip()
else:
f2.write(output)
output = ""

Basically, you need to loop over everything between your markers and put
them in a single entry, then send that one entry all at once instead of
piecemeal. 

I can come up with something a little more complete if you still need
more help.

-- 
David Rock
da...@graniteweb.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] formatting xml (again)

2016-12-27 Thread richard kappler
Using python 2.7 - I have a large log file we recorded of streamed xml data
that I now need to feed into another app for stress testing. The problem is
the data comes in 2 formats.

1. each 'event' is a full set of xml data with opening and closing tags +
x02 and x03 (stx and etx)

2. some events have all the xml data on one 'line' in the log, others are
in typical nested xml format with lots of white space and multiple 'lines'
in the log for each event, the first line of th e 'event' starting with an
stx and the last line of the 'event' ending in an etx.

Examples of how the data looks from an editor (gedit specifically in this
case):
1[x02]some stuffsome more
stuff>[x03]
2[x02]
3 
4   some stuff
5   somestuff
6
7[x03]

I have tried to feed this raw into our other app (Splunk) and the app reads
each line (gedit numbered line) as an event. I want everything in between
each stx and etx to be one event.

I have tried:

#
with open("original.log", 'r') as f1:
with open("new.log", 'a') as f2:
for line in f1:
line2 = line.replace("\n", "")
f2.write(line2)
##

Now this obviously doesn't work because, as stated above, each tag and
datum in the example above from lines 2 to 7 is on a different line, so
python is doing exactly as I tell it, it's stripping the \n and then
printing the line, but not concatenating everything between stx and etx on
one line, which is what I want it to do.

What I'm trying to do is collapse the 'expanded lines' between stx and etx
to one line, but I just can't wrap my head around how to do it. Or to put,
and do, it another way, how do I read each line from the original file, but
write it to another file so that everything from stx to etx, including stx
and etx, are on one line in the file?

regards Richard
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting strings

2015-05-08 Thread Steven D'Aprano
On Fri, May 08, 2015 at 05:11:49PM -0700, Danny Yoo wrote:

> Also, you can write a loop that goes from 1 to N by using range().  For 
> example:
> 
> 
> for n in range(1, N+1):
> print(n, 2*n)
> 
> 
> The while loop that you have does work, but the for loop here is more
> idiomatic in expressing the idea of "Do the following for this
> collection of values ..."

Why do so many beginners turn to while loops when they want to iterate 
over a fixed sequence?

I know that Learn Python The Hard Way teaches while loops first. I think 
that is a terrible idea. That's like going to a cookery class where 
for the first three weeks they teach you to chop vegetables with a 
spoon, and only in the fourth week say "Guess what? There's an easier 
way! Introducing the knife"


While-loops should be taught after for-loops. The fact that from a 
computer-science theoretical perspective while-loops are more 
fundamental is irrelevant. We don't teach people bitwise operators 
before teaching them arithmetic. Loops are no different.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting strings

2015-05-08 Thread Steven D'Aprano
On Thu, May 07, 2015 at 06:57:30PM +, Tudor, Bogdan - tudby001 wrote:
> Hi,
> 
> This is my first time.
> I am using python 3.4.3 on windows 7 64bit.
> 
> I am trying to make a binary counter that will prompt for and read a 
> decimal number (whole number). Then display all decimal numbers 
> starting from 1 up to and including the decimal number entered along 
> with the binary representation of the numbers to the screen.

Start by handling a single number:

py> def display_number(n):
... print(n, bin(n))
...
py> display_number(15)
15 0b

Now do a loop, displaying each number:

py> for i in range(1, 11):
... display_number(i)
...
1 0b1
2 0b10
3 0b11
4 0b100
5 0b101
6 0b110
7 0b111
8 0b1000
9 0b1001
10 0b1010



Does that help?



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting strings

2015-05-08 Thread Danny Yoo
> I am trying to make a binary counter that will prompt for and read a decimal 
> number (whole number). Then display all decimal numbers starting from 1 up to 
> and including the decimal number entered along with the binary representation 
> of the numbers to the screen.

You might consider writing a separate function toBinary() that takes
as input a number 'n' and returns its binary representation as a
string.  You're copying and pasting, and that's a sign that you've got
a block of code that you can *reuse*.  If you don't know how to write
functions, please ask!


Also, you can write a loop that goes from 1 to N by using range().  For example:


for n in range(1, N+1):
print(n, 2*n)


The while loop that you have does work, but the for loop here is more
idiomatic in expressing the idea of "Do the following for this
collection of values ..."

... Reading the code...


Ah.  You have a fixed number of variables to capture values such as
next_num_1, binary_num_1, next_num_2, binary_num_2, and so on.  But
this means you'll only be able to handle a fixed number of values,
where by "fixed", it looks like you've gone up to four.  :P

As you're noticing, this approach with capturing results with a fixed
number of variables isn't going to work well when we don't know how
many times we're walking through the loop.


Do you know about lists?  They allow you to hold onto a variable-sized
collection of values.  For example, let's say that we want to produce
the output:

###
1 2
2 4
3 6
4 8
5 10
...
###

Basically, our 2-times table.


Here's how we can do this.

#
## pseudocode
inputs = []
outputs = []
for x in range(10):
inputs.append(x)
outputs.append(x * 2)
#


Then we can get at any particular input/output by indexing the list at
the same position.  For example, we can print the inputs and outputs
like this:

#
inputs = []
outputs = []
for x in range(10):
inputs.append(x)
outputs.append(x * 2)
for (i, o) in zip(inputs, outputs):
   print (i,o)
#

and this takes an approach similar to what you've got, but it works
because it can hold onto all the results in a variable-sized list.



But that being said, for your particular program, you might not even
need to hold onto the entire collection of inputs and outputs at once.
Can you just do something like this instead?

###
for x in range(10):
doubled = x * 2
print(x, doubled)
###

where we interleave computation with output within the loop itself?
This has the advantage that we don't need to hold onto anything but
the very last thing we just computed, so it reduces the number of
things we're juggling to just the range that we're walking over, the
current value that we're walking, and the output from that current
value.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting strings

2015-05-08 Thread Dave Angel

On 05/07/2015 02:57 PM, Tudor, Bogdan - tudby001 wrote:

Hi,

This is my first time.


First time doing what?  Presumably the first time on this forum.  But 
what is your history of using Python, or of programming in general?



I am using python 3.4.3 on windows 7 64bit.

I am trying to make a binary counter that will prompt for and read a decimal 
number (whole number). Then display all decimal numbers starting from 1 up to 
and including the decimal number entered along with the binary representation 
of the numbers to the screen.

I expected nesting a bunch of loops over and over again would work, what I've 
realized is that there must be an easier way of coding this without repeating 
loops, I just cannot for the life of me work this out. What I'm doing at the 
moment is writing way to much code over and over again.

https://github.com/rks1337/binary-counting/blob/master/binary%20counting

Sorry I'm not sure how to use inline quoting on outlook online.



I can't answer for outlook, but normally you add stuff to your message 
by using copy/paste.  On Windows, that's Ctrl-C, Ctrl-V


I can't comment on the specifics of your code, since it's online rather 
than in your message.


--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] formatting strings

2015-05-08 Thread Tudor, Bogdan - tudby001
Hi,

This is my first time.
I am using python 3.4.3 on windows 7 64bit.

I am trying to make a binary counter that will prompt for and read a decimal 
number (whole number). Then display all decimal numbers starting from 1 up to 
and including the decimal number entered along with the binary representation 
of the numbers to the screen.

I expected nesting a bunch of loops over and over again would work, what I've 
realized is that there must be an easier way of coding this without repeating 
loops, I just cannot for the life of me work this out. What I'm doing at the 
moment is writing way to much code over and over again.

https://github.com/rks1337/binary-counting/blob/master/binary%20counting

Sorry I'm not sure how to use inline quoting on outlook online.

I will greatly appreciate any help!

Kind Regards.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-12 Thread eryksun
On Wed, Dec 11, 2013 at 8:37 AM, Mark Lawrence  wrote:
>
> print('{}:{}:{}'.format(now.hour, now.minute, now.year))
>
> Sorry I can never remember the formatting types to go between {} so look for
> them around here http://docs.python.org/3/library/string.html#formatstrings

For datetime's date, time, and datetime types, the __format__ method
passes the spec to strftime:

>>> t = datetime.datetime(2038,1,19,3,14,7)

>>> '{:%H:%M:%S}'.format(t)
'03:14:07'

If the format spec is empty, it uses __str__:

>>> format(t)
'2038-01-19 03:14:07'

But this is unrelated to timedelta, which lacks a custom __format__.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Jignesh Sutar
>
> Yes, because exe-time is not a ate, a point in time, but a time delta (a
> difference), thus does not hold the same attributes. Write out dir() on
> 'now' and on 'exe_time' to get more info. [dir() tells you about what info
> an object knows, and what methods it understands).]


Thanks Denis, that's very useful. I guess I was trying to deduce the same
information from the documentation but dir is a good way of double checking.


> This is a correct and general solution. Maybe worth being built-in, in
> fact, in my view.


Thanks for confirming. Yes, exactly, I was hoping to achieve this without
all the modulus calculations.

Cheers,
Jignesh



On 11 December 2013 21:18, spir  wrote:

> On 12/11/2013 06:40 PM, Jignesh Sutar wrote:
>
>> c = b-a
>> print "%s days, %.2dh: %.2dm: %.2ds" %
>> (c.days,c.seconds//3600,(c.seconds//60)%60, c.seconds%60)
>>
>
> This is a correct and general solution. Maybe worth being built-in, in
> fact, in my view.
>
> Denis
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread spir

On 12/11/2013 06:40 PM, Jignesh Sutar wrote:

c = b-a
print "%s days, %.2dh: %.2dm: %.2ds" %
(c.days,c.seconds//3600,(c.seconds//60)%60, c.seconds%60)


This is a correct and general solution. Maybe worth being built-in, in fact, in 
my view.


Denis

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread spir

On 12/11/2013 02:55 PM, Jignesh Sutar wrote:

Thanks Mark,

print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))


That works for;
now = datetime.now()

but not for;
exe_time = endTime-startTime


Yes, because exe-time is not a ate, a point in time, but a time delta (a 
difference), thus does not hold the same attributes. Write out dir() on 'now' 
and on 'exe_time' to get more info. [dir() tells you about what info an object 
knows, and what methods it understands).]


Denis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Danny Yoo
For reference, you can also see:


http://stackoverflow.com/questions/8906926/formatting-python-timedelta-objects

which shows a similar approach.  The accepted solution there uses the
divmod() function to simplify a little bit of the math.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Jignesh Sutar
Thanks folks, I think I have this as a working solution:

import datetime, time
a= datetime.datetime.now()
time.sleep(7.1564651443644)
b= datetime.datetime.now()
#for testing longer time periods
#a= datetime.datetime(2003, 8, 4, 8, 31, 4,0)
#b= datetime.datetime(2004, 8, 5, 19, 32, 6,0)
c = b-a
print "%s days, %.2dh: %.2dm: %.2ds" %
(c.days,c.seconds//3600,(c.seconds//60)%60, c.seconds%60)

The attributes for timedelta seem only to be days, seconds and microseconds
only. Nonetheless these can be used to deduce HH:MM:SS.

Thanks,
Jignesh


On 11 December 2013 16:21, Ricardo Aráoz  wrote:

> El 11/12/13 10:37, Mark Lawrence escribió:
>
>  On 11/12/2013 13:12, Jignesh Sutar wrote:
>>
>>> print str(exe_time).split('.')[0]
>>> Sorry, I guess my question was why I can't use something similar to
>>> below on exe_time (of type datetime.timedelta)? Rather than doing string
>>> manipulation on decimals or colons to extract the same.
>>>
>>> now = datetime.now()
>>> print now.hour
>>> print now.minute
>>> print now.year
>>>
>>>
>> Old style
>>
>> print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))
>>
>> New style
>>
>> print('{}:{}:{}'.format(now.hour, now.minute, now.year))
>>
>> Sorry I can never remember the formatting types to go between {} so look
>> for them around here http://docs.python.org/3/library/string.html#
>> formatstrings
>>
>>
>
> Or just use strftime() :
>
> >>> import datetime
> >>> n = datetime.datetime.now()
> >>> n.strftime('%H:%M:%S')
> '13:19:04'
>
> >>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Ricardo Aráoz

El 11/12/13 10:37, Mark Lawrence escribió:

On 11/12/2013 13:12, Jignesh Sutar wrote:

print str(exe_time).split('.')[0]
Sorry, I guess my question was why I can't use something similar to
below on exe_time (of type datetime.timedelta)? Rather than doing string
manipulation on decimals or colons to extract the same.

now = datetime.now()
print now.hour
print now.minute
print now.year



Old style

print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))

New style

print('{}:{}:{}'.format(now.hour, now.minute, now.year))

Sorry I can never remember the formatting types to go between {} so 
look for them around here 
http://docs.python.org/3/library/string.html#formatstrings





Or just use strftime() :

>>> import datetime
>>> n = datetime.datetime.now()
>>> n.strftime('%H:%M:%S')
'13:19:04'
>>>

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Mark Lawrence

[top posting fixed]



On 11 December 2013 13:37, Mark Lawrence mailto:breamore...@yahoo.co.uk>> wrote:

On 11/12/2013 13:12, Jignesh Sutar wrote:

 print str(exe_time).split('.')[0]
Sorry, I guess my question was why I can't use something similar to
below on exe_time (of type datetime.timedelta)? Rather than
doing string
manipulation on decimals or colons to extract the same.

now = datetime.now()
print now.hour
print now.minute
print now.year


Old style

print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))

New style

print('{}:{}:{}'.format(now.__hour, now.minute, now.year))

Sorry I can never remember the formatting types to go between {} so
look for them around here
http://docs.python.org/3/__library/string.html#__formatstrings


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence


On 11/12/2013 13:55, Jignesh Sutar wrote:> Thanks Mark,


print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))


That works for;
now = datetime.now()

but not for;
exe_time = endTime-startTime


Thanks,
Jignesh




You'll have to do the sums yourself based on the data for timedelta here 
http://docs.python.org/3/library/datetime.html#timedelta-objects, 
alternatively download a third party module such as 
http://labix.org/python-dateutil.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Jignesh Sutar
Thanks Mark,

print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))


That works for;
now = datetime.now()

but not for;
exe_time = endTime-startTime


Thanks,
Jignesh


On 11 December 2013 13:37, Mark Lawrence  wrote:

> On 11/12/2013 13:12, Jignesh Sutar wrote:
>
>> print str(exe_time).split('.')[0]
>> Sorry, I guess my question was why I can't use something similar to
>> below on exe_time (of type datetime.timedelta)? Rather than doing string
>> manipulation on decimals or colons to extract the same.
>>
>> now = datetime.now()
>> print now.hour
>> print now.minute
>> print now.year
>>
>>
> Old style
>
> print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))
>
> New style
>
> print('{}:{}:{}'.format(now.hour, now.minute, now.year))
>
> Sorry I can never remember the formatting types to go between {} so look
> for them around here http://docs.python.org/3/library/string.html#
> formatstrings
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask what
> you can do for our language.
>
> Mark Lawrence
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Mark Lawrence

On 11/12/2013 13:12, Jignesh Sutar wrote:

print str(exe_time).split('.')[0]
Sorry, I guess my question was why I can't use something similar to
below on exe_time (of type datetime.timedelta)? Rather than doing string
manipulation on decimals or colons to extract the same.

now = datetime.now()
print now.hour
print now.minute
print now.year



Old style

print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))

New style

print('{}:{}:{}'.format(now.hour, now.minute, now.year))

Sorry I can never remember the formatting types to go between {} so look 
for them around here 
http://docs.python.org/3/library/string.html#formatstrings


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Jignesh Sutar
>
> print str(exe_time).split('.')[0]


Sorry, I guess my question was why I can't use something similar to below
on exe_time (of type datetime.timedelta)? Rather than doing string
manipulation on decimals or colons to extract the same.

now = datetime.now()
print now.hour
print now.minute
print now.year


On 11 December 2013 12:43, David Robinow  wrote:

> On Wed, Dec 11, 2013 at 5:55 AM, Jignesh Sutar  wrote:
> > Hi,
> >
> > I've googled around extensively to try figure this out assuming it
> should be
> > straight forward (and it probably is) but I'm clearly missing something.
> >
> > I'm trying to get the total run time of the program but have the final
> time
> > being displayed in a particular format. I.e. without the seconds in
> > milliseconds decimal points and just to customize it a bit more.
> >
> > import time
> > from datetime import datetime
> > startTime = datetime.now()
> > time.sleep(5.1564651443644)
> > endTime = datetime.now()
> > exe_time = endTime-startTime
> >
> > print type(startTime)
> > print type(endTime)
> > print type(exe_time)
> >
> > print "startTime: ", startTime
> > print "endTime:", endTime
> > print "exe_time: ", exe_time #how to format this to "D Days, HH: MM: SS"
> ?
> > #exe_time:  0:00:05.156000
> > #desired 0 Days, 0h: 00:m: 05s
> >
> print str(exe_time).split('.')[0]
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread David Robinow
On Wed, Dec 11, 2013 at 5:55 AM, Jignesh Sutar  wrote:
> Hi,
>
> I've googled around extensively to try figure this out assuming it should be
> straight forward (and it probably is) but I'm clearly missing something.
>
> I'm trying to get the total run time of the program but have the final time
> being displayed in a particular format. I.e. without the seconds in
> milliseconds decimal points and just to customize it a bit more.
>
> import time
> from datetime import datetime
> startTime = datetime.now()
> time.sleep(5.1564651443644)
> endTime = datetime.now()
> exe_time = endTime-startTime
>
> print type(startTime)
> print type(endTime)
> print type(exe_time)
>
> print "startTime: ", startTime
> print "endTime:", endTime
> print "exe_time: ", exe_time #how to format this to "D Days, HH: MM: SS" ?
> #exe_time:  0:00:05.156000
> #desired 0 Days, 0h: 00:m: 05s
>
print str(exe_time).split('.')[0]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] formatting datetime.timedelta to "HH:MM:SS"

2013-12-11 Thread Jignesh Sutar
Hi,

I've googled around extensively to try figure this out assuming it should
be straight forward (and it probably is) but I'm clearly missing something.

I'm trying to get the total run time of the program but have the final time
being displayed in a particular format. I.e. without the seconds in
milliseconds decimal points and just to customize it a bit more.

import time
from datetime import datetime
startTime = datetime.now()
time.sleep(5.1564651443644)
endTime = datetime.now()
exe_time = endTime-startTime

print type(startTime)
print type(endTime)
print type(exe_time)
print "startTime: ", startTime
print "endTime:", endTime
print "exe_time: ", exe_time #how to format this to "D Days, HH: MM: SS" ?
#exe_time:  0:00:05.156000
#desired 0 Days, 0h: 00:m: 05s


Thanks in advance,
Jignesh
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting questions regarding datetime.isoformat()

2012-09-06 Thread eryksun
On Thu, Sep 6, 2012 at 3:50 AM, Dave Angel  wrote:
> On 09/06/2012 03:35 AM, eryksun wrote:
>> 
>> Or you could use datetime.now(dateutil.tz.tzutc()) for a UTC tzinfo.
>> It doesn't matter if you're only interested in the timedelta.
>
> Actually, it can matter.  Whenever possible, produce all times as UTC
> and do your manipulations (eg. difference) in that space.  With local
> time, there are times that don't exist and times that are ambiguous, one
> in the fall and one in the spring, due to setting the clock forward or back.
>
> i don't know for sure if it matters here, but I've found it's better to
> work that way.

These are aware datetime objects. See the datetime docs for supported
operations, case 3, timedelta = datetime1 - datetime2:

http://docs.python.org/library/datetime#datetime.datetime.tzinfo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting questions regarding datetime.isoformat()

2012-09-06 Thread Peter Otten
staticsafe wrote:

> Hello,
> 
> I am running Python 2.6.6 on a Debian Squeeze system. I am using two
> modules in this bit of code - datetime and python-tvrage (available on
> pypy here: http://pypi.python.org/pypi/python-tvrage/).
> 
> My goal is to find the time remaining until a certain show airs. Here is
> some code I have written so far:
> 
> #!/usr/bin/env python
> from tvrage import quickinfo
> from datetime import tzinfo, timedelta, datetime
> 
> showinfo = quickinfo.fetch("Warehouse 13")
> nextairdate = showinfo['RFC3369']
> now = datetime.now().isoformat()
> 
> Now for my question/problem.
> 
> In [68]: showinfo['RFC3339']
> Out[68]: '2012-09-10T21:00:00-4:00'
> 
> In [72]: datetime.now().isoformat()
> Out[72]: '2012-09-05T22:47:46.061688'
> 
> isoformat() is in a different format than the value returned by the API.
> My question is how would one format both values so that I can perform a
> timedelta on them as is the purpose of my code?
> 
> I hope I have provided the right amount of detail for my question.

After some trial and error:

import dateutil.parser # python-dateutil
import pytz # python-tz
import datetime

show_start = dateutil.parser.parse("2012-09-10T21:00:00-0400")
now = datetime.datetime.now(pytz.timezone("EST"))

print "show starts: ", show_start
print "current time:", now
print "days to go:  ", show_start - now

(Caveat: I'm using Python 2.7)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting questions regarding datetime.isoformat()

2012-09-06 Thread eryksun
On Wed, Sep 5, 2012 at 11:00 PM, staticsafe  wrote:
>
> In [68]: showinfo['RFC3339']
> Out[68]: '2012-09-10T21:00:00-4:00'

You can parse the ISO format using the dateutil module:

http://labix.org/python-dateutil

>>> from dateutil.parser import parse
>>> show_time = parse('2012-09-10T21:00:00-4:00')

This produces a time-zone aware datetime object. You can pass its
tzinfo to datetime.now() to get the current time as an aware datetime
object:

>>> now = datetime.now(show_time.tzinfo)

Or you could use datetime.now(dateutil.tz.tzutc()) for a UTC tzinfo.
It doesn't matter if you're only interested in the timedelta.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Formatting questions regarding datetime.isoformat()

2012-09-05 Thread staticsafe
Hello,

I am running Python 2.6.6 on a Debian Squeeze system. I am using two
modules in this bit of code - datetime and python-tvrage (available on
pypy here: http://pypi.python.org/pypi/python-tvrage/).

My goal is to find the time remaining until a certain show airs. Here is
some code I have written so far:

#!/usr/bin/env python
from tvrage import quickinfo
from datetime import tzinfo, timedelta, datetime

showinfo = quickinfo.fetch("Warehouse 13")
nextairdate = showinfo['RFC3369']
now = datetime.now().isoformat()

Now for my question/problem.

In [68]: showinfo['RFC3339']
Out[68]: '2012-09-10T21:00:00-4:00'

In [72]: datetime.now().isoformat()
Out[72]: '2012-09-05T22:47:46.061688'

isoformat() is in a different format than the value returned by the API.
My question is how would one format both values so that I can perform a
timedelta on them as is the purpose of my code?

I hope I have provided the right amount of detail for my question.

Thanks,
-- 
staticsafe
http://staticsafe.ca
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting sql Was: Some help Please

2012-02-15 Thread James Reynolds
On Wed, Feb 15, 2012 at 1:30 PM, Alan Gauld wrote:

> On 15/02/12 18:03, James Reynolds wrote:
>
>  >In you table the acc_id is 'mn0001'
>> >In your sql Acc_ID = 'MN0001'
>> >Why the difference in case?
>>
>> Normally, sql doesn't care about case with respect to table names. I
>> believe in certain implementations they are always lower case, even if
>> you pass an upper.
>>
>
> The issue is not the table (or even column name) its the value within it.
> Comparing 'mn0001' to 'MN0001' will fail.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>


I think this depends on the settings of the column and what you have set in
your sql statement.

Example:

if ('j' = 'J')
select 'True'
else
select 'False'

This comes out True

if ('j' = 'k')
select 'True'
else
select 'False'

This comes out False

I suppose this could be by implementation, but at least in sql server, I
think Oracle, and maybe some others, you have to set the database (or
column) to case sensitive by changing it through a collation statement.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting sql Was: Some help Please

2012-02-15 Thread Alan Gauld

On 15/02/12 18:03, James Reynolds wrote:


>In you table the acc_id is 'mn0001'
>In your sql Acc_ID = 'MN0001'
>Why the difference in case?

Normally, sql doesn't care about case with respect to table names. I
believe in certain implementations they are always lower case, even if
you pass an upper.


The issue is not the table (or even column name) its the value within 
it. Comparing 'mn0001' to 'MN0001' will fail.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting sql Was: Some help Please

2012-02-15 Thread James Reynolds
On Wed, Feb 15, 2012 at 12:13 PM, bob gailer  wrote:

> Welcome to python help. We are a few volunteers who donate time to assist.
>
> To assist you better:
> 1 - provide a meaningful subject line - such as "formatting sql"
> 2 - tell us what OS and Python version you are using.
> 3 - what is your prior Python experience?
>
>
> On 2/15/2012 9:17 AM, JOSEPH MARTIN MPALAKA wrote:
>
>> take an example of updating Bank Accounts,
>> gaving the following table:
>>
>> acc_id  acc_namestanding_Balance
>> mn0001  computer 2
>>
>> my problem is how can i credit the standing balance from user data,as
>> in making a deposit onto the computer account, using the code below:-
>>
>>
>>
>> import MySQLdb as mdb
>> import sys
>>
>> con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings');
>>
>> dep = input('Enter Amount: ')
>>
>> cur.execute("UPDATE accounts SET Standing_Amount =
>> (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'")
>>
> In you table the acc_id is 'mn0001'
> In your sql Acc_ID = 'MN0001'
> Why the difference in case?
> Why the () around Standing_Amount + dep?
>
>
>>conn.commit()
>>
>> HOw do i format "dep" in order to be added onto the standing_Amount,to
>> make an increment?
>>
>> Please, is it the same thing with the withdrawing format, in case i
>> want to decrement the account as in withdrawing??
>>
>>
>> joseph
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>


Normally, sql doesn't care about case with respect to table names. I
believe in certain implementations they are always lower case, even if you
pass an upper.

The problem, as Bob pointed out above, cur.execute("UPDATE accounts SET
Standing_Amount =
(Standing_Amount + dep) WHERE Acc_ID = 'MN0001'")

here, specifically, (Standing_Amount + dep)

Sql isn't going to have any idea what "dep" is when passed, because it is
going to see a string called "Dep". Well, it will know what it is, it will
be a string and will through an error that it can't add a string and
integer.
When i want to update a value in sql, normally i extract to python, do the
math there, and then update. You can do this in sql if you prefer and I'm
sure there are good reasons for doing it, I'm just more comfortable working
in python than I am sql.

Also, when passing variables to SQL, if you are doing raw queries and not
using some ORM, I would get used to using the "?" within the sql string and
then passing your variables in the following list. Otherwise, you are going
to leave yourself open to injection attacks (provided you are doing direct
string manipulations).

To do this in sql, you need to run a select statement first, saving the
results to a @variable. use that @variable later (after passing in an
integer) to add the two numbers.

To do this in python, also run a select statement, save it to some python
variable. Add your new result to it, and send that new result along to the
DB using your update query.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] formatting sql Was: Some help Please

2012-02-15 Thread bob gailer

Welcome to python help. We are a few volunteers who donate time to assist.

To assist you better:
1 - provide a meaningful subject line - such as "formatting sql"
2 - tell us what OS and Python version you are using.
3 - what is your prior Python experience?


On 2/15/2012 9:17 AM, JOSEPH MARTIN MPALAKA wrote:

take an example of updating Bank Accounts,
gaving the following table:

acc_id  acc_namestanding_Balance
mn0001  computer 2

my problem is how can i credit the standing balance from user data,as
in making a deposit onto the computer account, using the code below:-



import MySQLdb as mdb
import sys

con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings');

dep = input('Enter Amount: ')

 cur.execute("UPDATE accounts SET Standing_Amount =
(Standing_Amount + dep) WHERE Acc_ID = 'MN0001'")

In you table the acc_id is 'mn0001'
In your sql Acc_ID = 'MN0001'
Why the difference in case?
Why the () around Standing_Amount + dep?



conn.commit()

HOw do i format "dep" in order to be added onto the standing_Amount,to
make an increment?

Please, is it the same thing with the withdrawing format, in case i
want to decrement the account as in withdrawing??


joseph












--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting a string

2011-02-01 Thread Becky Mcquilling
Thanks, as always.  It all works.

Becky

On Tue, Feb 1, 2011 at 7:08 AM, Alan Gauld wrote:

> "Becky Mcquilling"  wrote
>
>
>  Basically, I need to format a string as an example:
>>
>> "He is {what}.format("{wild}")
>>
>> I want to insert wild in place of what and output the resulting text WITH
>> the curly braces.
>>
>
>  what = 'wild'
 "Here is {what}".format(what=what)

>>> 'Here is wild'
>
>> "Here is {what}".format(what='wild')

>>> 'Here is wild'
>
>> "Here is {{what}}".format(what='wild')

>>> 'Here is {what}'
>
>> "Here is {what}".format(what='{wild}')

>>> 'Here is {wild}'
>
>>

> Take your pick :-)
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting a string

2011-02-01 Thread Alan Gauld

"Becky Mcquilling"  wrote


Basically, I need to format a string as an example:

"He is {what}.format("{wild}")

I want to insert wild in place of what and output the resulting text 
WITH

the curly braces.



what = 'wild'
"Here is {what}".format(what=what)

'Here is wild'

"Here is {what}".format(what='wild')

'Here is wild'

"Here is {{what}}".format(what='wild')

'Here is {what}'

"Here is {what}".format(what='{wild}')

'Here is {wild}'




Take your pick :-)

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting a string

2011-02-01 Thread Karim


Complete test copy & paste:

karim@Requiem4Dream:~$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "He is {what}".format(what="{wild}")
'He is {wild}'
>>>

I don't get the missing "."   ?!

Regards
Karim

On 02/01/2011 01:35 PM, col speed wrote:
You're missing a "." that if your computer is the same as mine, looks 
like something left behind by a mosquito


On 1 February 2011 18:33, Karim > wrote:



Hello,

>>> "He is {what}".format(what="{wild}")
'He is {wild}'

Regards
Karim


On 02/01/2011 09:44 AM, Becky Mcquilling wrote:

Quick question to the group to solve an immediate problem and
then if anyone has a dead simple reference on formatting strings
it would be greatly appreciated as I'm finding this to be pretty
confusing.

Basically, I need to format a string as an example:

"

I want to insert wild in place of what and output the resulting
text WITH the curly braces.  This is not the actual code but is
the idea of what I need to do.

Thanks all,

Becky


___
Tutor maillist  -Tutor@python.org  
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  - Tutor@python.org 
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




--




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting a string

2011-02-01 Thread col speed
You're missing a "." that if your computer is the same as mine, looks like
something left behind by a mosquito

On 1 February 2011 18:33, Karim  wrote:

>
> Hello,
>
> >>> "He is {what}".format(what="{wild}")
> 'He is {wild}'
>
> Regards
> Karim
>
>
> On 02/01/2011 09:44 AM, Becky Mcquilling wrote:
>
> Quick question to the group to solve an immediate problem and then if
> anyone has a dead simple reference on formatting strings it would be greatly
> appreciated as I'm finding this to be pretty confusing.
>
> Basically, I need to format a string as an example:
>
>  "
>
>  I want to insert wild in place of what and output the resulting text WITH
> the curly braces.  This is not the actual code but is the idea of what I
> need to do.
>
>  Thanks all,
>
>  Becky
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription 
> options:http://mail.python.org/mailman/listinfo/tutor
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


--
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting a string

2011-02-01 Thread Karim


Hello,

>>> "He is {what}".format(what="{wild}")
'He is {wild}'

Regards
Karim

On 02/01/2011 09:44 AM, Becky Mcquilling wrote:
Quick question to the group to solve an immediate problem and then if 
anyone has a dead simple reference on formatting strings it would be 
greatly appreciated as I'm finding this to be pretty confusing.


Basically, I need to format a string as an example:

"

I want to insert wild in place of what and output the resulting text 
WITH the curly braces.  This is not the actual code but is the idea of 
what I need to do.


Thanks all,

Becky


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Formatting a string

2011-02-01 Thread Becky Mcquilling
Quick question to the group to solve an immediate problem and then if anyone
has a dead simple reference on formatting strings it would be greatly
appreciated as I'm finding this to be pretty confusing.

Basically, I need to format a string as an example:

"He is {what}.format("{wild}")

I want to insert wild in place of what and output the resulting text WITH
the curly braces.  This is not the actual code but is the idea of what I
need to do.

Thanks all,

Becky
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting date/time

2010-08-04 Thread Eduardo Vieira
On Wed, Aug 4, 2010 at 12:45 PM, Eric Hamiter  wrote:
> There are a few solutions here:
>
> http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0
>
> Eric
>
>
> On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira 
> wrote:
>>
>> I'm trying this example from python docs:
>> from time import gmtime, strftime
>> strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
>>
>> Output = 'Wed, 04 Aug 2010 17:58:42 +'
>> Is not there a string formatting option for the day without a leading
>> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +'
>>
>> It looks like it's not in the docs.
>>
>> Thanks
>>
>> Eduardo
>> ___
>> Tutor maillist  -  tu...@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>

Thank you for the link. Just what I needed to know. The option %e
didn't work for me, but I will use the other suggestions in the
answers.

Eduardo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting date/time

2010-08-04 Thread Joel Goldstick
On Wed, Aug 4, 2010 at 2:45 PM, Eric Hamiter  wrote:

> There are a few solutions here:
>
>
> http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0
>
> Eric
>
>
>
> On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira wrote:
>
>> I'm trying this example from python docs:
>> from time import gmtime, strftime
>> strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
>>
>> Output = 'Wed, 04 Aug 2010 17:58:42 +'
>> Is not there a string formatting option for the day without a leading
>> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +'
>>
>> It looks like it's not in the docs.
>>
>> Thanks
>>
>> Eduardo
>>
>
%e worked for me on Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)


-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting date/time

2010-08-04 Thread Eric Hamiter
There are a few solutions here:

http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0

Eric


On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira wrote:

> I'm trying this example from python docs:
> from time import gmtime, strftime
> strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
>
> Output = 'Wed, 04 Aug 2010 17:58:42 +'
> Is not there a string formatting option for the day without a leading
> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +'
>
> It looks like it's not in the docs.
>
> Thanks
>
> Eduardo
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Formatting date/time

2010-08-04 Thread Eduardo Vieira
I'm trying this example from python docs:
from time import gmtime, strftime
strftime("%a, %d %b %Y %H:%M:%S +", gmtime())

Output = 'Wed, 04 Aug 2010 17:58:42 +'
Is not there a string formatting option for the day without a leading
zero? Like: 'Wed, 4 Aug 2010 17:58:42 +'

It looks like it's not in the docs.

Thanks

Eduardo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-09 Thread Alan Gauld


"Lowell Tackett"  wrote


In the meantime, posing this query took me somewhere I hadn't imagined...
I got turned on to the 'Gmane' mailsite, which pretty much solved all my 
issues,

plus presented a much nicer 'reading room'.


I actually use it as a news feed into Outlook Express.
I only occasionally use the gmane web site.

Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-08 Thread Lowell Tackett

>From the virtual desk of Lowell Tackett  



--- On Fri, 1/8/10, spir  wrote:

> From: spir 
> Subject: Re: [Tutor] formatting*
> To: tutor@python.org
> Date: Friday, January 8, 2010, 7:27 AM
> Lowell Tackett dixit:
> 
> Yo, that's because you're viewing the source as plain text,...
> 
> Denis
> 
> 
> la vita e estrany
> 

In the meantime, posing this query took me somewhere I hadn't imagined...I got 
turned on to the 'Gmane' mailsite, which pretty much solved all my issues, plus 
presented a much nicer 'reading room'.  After rummaging around awhile I've got 
the site figured out enough to make good use of it (a tip of the hat to Alan 
Gauld for the reference to that great site).


  

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-08 Thread spir
Lowell Tackett dixit:

> An odd aside, however--I went into the Tutor Archives forum and pulled up the 
> Page Source (HTML formatting template) and lo and behold all my paragraphs 
> were correctly formatted (i.e. page-wrapped just as they had been when they 
> left my mail notepad) and displayed correctly--on the source page.  So,who 
> knows...(?)

Yo, that's because you're viewing the source as plain text, so your viewer 
(browser, probably) can consistently wrap lines, adapting to window width. But 
probably archives impose a kind of formatting that prevents such adaptation 
[imo, this is a flaw (like imposing an absolute text size), but it's an 
opinion].

Denis


la vita e estrany

http://spir.wikidot.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-07 Thread Lowell Tackett
Well, Ok then, I have switched to plain text to transmit this response.  I will 
follow it over to the archive forum to see how the difference works.

In the meantime...this back-and-forth dialog has at least made me aware of 
gmane, a website I had not been aware of.  Interesting place.  I was over 
there, looking around, and trying to figure it out.  Found some of this 
correspondence "set" there, pretty much in isolation.

It's a quirky place that I'm trying to figure out.  Only a few of the most 
current items seem to be available (unlike the Tutor Archive forum, where an 
entire month's submittals are all lined up and available for sequential 
reading).  Does one need to "sign up" in someway or another to make the entire 
site available?

Thanks for your help and input with all of this.
>From the virtual desk of Lowell Tackett  


--- On Thu, 1/7/10, Alan Gauld  wrote:

From: Alan Gauld 
Subject: Re: [Tutor] formatting*
To: tutor@python.org
Date: Thursday, January 7, 2010, 7:25 PM


"Lowell Tackett"  wrote

> Well, not a lot of luck. What I use is Yahoo mail (whatever that is---a 
> "thick" client??),
> and thus far I can't find any tool bars that offer help.

A thick client is an application that runs on your desktop with built in 
intelligence.
A thin client is a GUI within a browser that has all the intelligence on a
server - typically a web app.

Yahoo is a thin client. As it happens I use it too.

You should find at the end of the subject line on outgoing messages
an option to switch to plain text. Select that and you should find your
line breaks are recognised. (HTML does not recognise your line
breaks and tries to leave formatting to the browser. The archive
page obviously gets confused by this! But using HTML to a mailing
list causes other problems too so its best to send as plain text)

HTH,

-- Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



  

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-07 Thread Alan Gauld


"Lowell Tackett"  wrote

Well, not a lot of luck. What I use is Yahoo mail (whatever that is---a 
"thick" client??),

and thus far I can't find any tool bars that offer help.


A thick client is an application that runs on your desktop with built in 
intelligence.

A thin client is a GUI within a browser that has all the intelligence on a
server - typically a web app.

Yahoo is a thin client. As it happens I use it too.

You should find at the end of the subject line on outgoing messages
an option to switch to plain text. Select that and you should find your
line breaks are recognised. (HTML does not recognise your line
breaks and tries to leave formatting to the browser. The archive
page obviously gets confused by this! But using HTML to a mailing
list causes other problems too so its best to send as plain text)

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-07 Thread Lowell Tackett
Well, not a lot of luck.  What I use is Yahoo mail (whatever that is---a 
"thick" client??), and thus far I can't find any tool bars that offer help.

An odd aside, however--I went into the Tutor Archives forum and pulled up the 
Page Source (HTML formatting template) and lo and behold all my paragraphs were 
correctly formatted (i.e. page-wrapped just as they had been when they left my 
mail notepad) and displayed correctly--on the source page.  So,who knows...(?)

>From the virtual desk of Lowell Tackett  


--- On Thu, 1/7/10, ALAN GAULD  wrote:

From: ALAN GAULD 
Subject: Re: [Tutor] formatting*
To: "Lowell Tackett" , tutor@python.org
Date: Thursday, January 7, 2010, 5:36 PM


> I'm using Mandrake 10.1 [Linux] OS to view the internet thru Firefox.  
> In my mailbox, everything is fine--my stuff formats well (and when it 
> comes back to me as Tutor 'mail' it also formats correctly).
>
> The problem is over at the Tutor Archives (mail.python.org/pipermail/tutor), 
> i.e., the Tutor forum site.  That's where whatever I composed formats 
> out with no line wrap, and a paragraph becomes a single line, 

Yes I see that. I don't use that archive I normally use gmane...

However that is probably down to whatever mail program you are 
using to post with. Is it a web client or a full blown thick client mail 
tool like Thunderbird?

Whichever, it probably has an option to automatically wrap sent text
and I suspect you have that turned off. A good value is usually 
around 70 or 80 chars.

FWIW I have the opposite problem using gmail, it consistently wraps 
my text prematurely leaving my paragraphs badly formatted. And I 
can't find where to change the setting!

HTH,

Alan G.


  




  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-07 Thread ALAN GAULD


> I'm using Mandrake 10.1 [Linux] OS to view the internet thru Firefox.  
> In my mailbox, everything is fine--my stuff formats well (and when it 
> comes back to me as Tutor 'mail' it also formats correctly).
>
> The problem is over at the Tutor Archives (mail.python.org/pipermail/tutor), 
> i.e., the Tutor forum site.  That's where whatever I composed formats 
> out with no line wrap, and a paragraph becomes a single line, 

Yes I see that. I don't use that archive I normally use gmane...

However that is probably down to whatever mail program you are 
using to post with. Is it a web client or a full blown thick client mail 
tool like Thunderbird?

Whichever, it probably has an option to automatically wrap sent text
and I suspect you have that turned off. A good value is usually 
around 70 or 80 chars.

FWIW I have the opposite problem using gmail, it consistently wraps 
my text prematurely leaving my paragraphs badly formatted. And I 
can't find where to change the setting!

 HTH,

Alan G.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-07 Thread Lowell Tackett
I'm using Mandrake 10.1 [Linux] OS to view the internet thru Firefox.  In my 
mailbox, everything is fine--my stuff formats well (and when it comes back to 
me as Tutor 'mail' it also formats correctly).

The problem is over at the Tutor Archives (mail.python.org/pipermail/tutor), 
i.e., the Tutor forum site.  That's where whatever I composed formats out with 
no line wrap, and a paragraph becomes a single line, stretching out however far 
it needs to.  In all the time I've been perusing the forum (before jumping in 
to participate) I have seen "occasionally" a contributor's offering will suffer 
the same fate.  Now my entries are doing so as well.  I don't know if everybody 
who goes to the forum site sees these format problems as I do (apparently 
not--from your response), but there they are on my screen.

Hope I've answered your questions with some degree of understandability.

>From the virtual desk of Lowell Tackett  


--- On Thu, 1/7/10, Alan Gauld  wrote:

From: Alan Gauld 
Subject: Re: [Tutor] formatting*
To: tutor@python.org
Date: Thursday, January 7, 2010, 4:59 PM


"Lowell Tackett"  wrote 
> *No, not in Python...in this Tutor format. How do I include line breaks in 
> text so the lines in the Tutor Archives wrap (as opposed to stretching 
> halfway to Idaho)?

How are you viewing the messages?
I have never seen that problem. Are you using a web browser or a newsreader?
Which OS, which site?


-- Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting*

2010-01-07 Thread Alan Gauld


"Lowell Tackett"  wrote 
*No, not in Python...in this Tutor format. 
How do I include line breaks in text so the lines in 
the Tutor Archives wrap (as opposed to stretching halfway to Idaho)?


How are you viewing the messages?
I have never seen that problem. 
Are you using a web browser or a newsreader?

Which OS, which site?


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] formatting*

2010-01-07 Thread Lowell Tackett
*No, not in Python...in this Tutor format.  How do I include line breaks in 
text so the lines in the Tutor Archives wrap (as opposed to stretching halfway 
to Idaho)?

>From the virtual desk of Lowell Tackett  



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting zip module arguments correctly

2009-04-05 Thread Mark Tolonen
The error indicates your source file cannot be read.  Did you have it open in 
an editor that locks it for exclusive use when you ran your program?

Also, the command:

zipfile.ZipFile(target, 'w').write(source)

writes backup_list to the target zipfile, and returns None, assigning the 
return value to zip_command and passing that to os.system makes no sense.  The 
command above will throw an exception if anything goes wrong (as you found), so 
the following code is probably what you want:

try:
zipfile.ZipFile(target, 'w').write(source)
except IOError:
print('Backup Failed')
else:
print('Successful backup to',target)

-Mark


  "Benjamin Serrato"  wrote in message 
news:dde7cc5d0904051354v1c103fb2wf28f182734970...@mail.gmail.com...
  Please tell me why this code fails. I am new and I don't understand why my 
formatting of my zip arguments is incorrect. Since I am unsure how to 
communicate best so I will show the code, the error message, and what I believe 
is happening.


#!c:\python30# Filename: backup_ver5.pyimport osimport time
import zipfilesource = r'C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_list'target_dir = r'C:\Documents and Settings\Benjamin 
Serrato\My Documents\python\backup_dir'
today = target_dir + os.sep + time.strftime('%Y%m%d') now = 
time.strftime('%H%M%S')comment = input('Enter a comment --> ')if len(comment) 
== 0: target = today + os.sep + now + '.zip'
else:   target = today + os.sep + now + '_' + \ comment.replace(' ', '_') + 
'.zip'if not os.path.exists(today): os.mkdir(today) print('Successfully created 
directory', today)
print(target)print(source)zip_command = zipfile.ZipFile(target, 
'w').write(source)if os.system(zip_command) == 0:   print('Successful 
backup to', target)else:  print('Backup FAILED')
I receive this error message:

  Enter a comment -->
  C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_dir\200904
  05\154956.zip
  C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list
  Traceback (most recent call last):
File "C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_ve
  r5.py", line 32, in 
  zip_command = zipfile.ZipFile(target, 'w').write(source)
File "c:\python30\lib\zipfile.py", line 1031, in write
  fp = io.open(filename, "rb")
File "C:\Python30\lib\io.py", line 222, in open
  closefd)
File "C:\Python30\lib\io.py", line 615, in __init__
  _fileio._FileIO.__init__(self, name, mode, closefd)
  IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\\Benjamin 
Ser
  rato\\My Documents\\python\\backup_list'


  The two print tests before zip_command is assigned tell me that the two 
strings are being passed to zipfile.ZipFile() correctly. The traceback tells me 
I am not calling zipfile.ZipFile() correctly. The error in __init__ makes me 
more sure of this. Last, the problem seems to be that I am causing my path 
string to have double backslashes. I can't follow why the IOError shows that.

  I used this site to figure out how to use zipfile. zipfile is a class, I 
import it at the start of the program then I use it and its primary method. I 
pass the file I would like to write to zipfile.ZipFile('file to write', 'mode') 
and set the program to open an object set to be writable. Then the command 
writes the file to the destination folder with a sub-method like so, 
"".zipfile('files to write').

  Where am I going wrong?





--


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


Re: [Tutor] Formatting zip module arguments correctly

2009-04-05 Thread Alan Gauld


"Benjamin Serrato"  wrote


formatting of my zip arguments is incorrect. Since I am unsure how to
communicate best so I will show the code, the error message, and what I
believe is happening.


Thats pretty close to communicating the best way! :-)


zip_command = zipfile.ZipFile(target, 'w').write(source)

if os.system(zip_command) == 0:


I didn't think you needed to call os.system when using the zipfile module?
The module should do everything itself... But your error occurs on the
line above and it says:


 File "C:\Python30\lib\io.py", line 615, in __init__
   _fileio._FileIO.__init__(self, name, mode, closefd)
IOError: [Errno 13] Permission denied: 'C:\\Documents and 
Settings\\Benjamin

Serrato\\My Documents\\python\\backup_list'


You don't have permission to write that file.
Now either you don't have the right permissions on the OS or the file
is locked by another program?

But it looks like this is the file you are passing to zipfile?
I thought the filename in the constructor was supposed to
be the actual zipfile name (ie the output!) not the file you
are trying to zip? But I'm no zipfile module expert so I may
be wrong there.

HTH,

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/l2p/ 



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


Re: [Tutor] Formatting zip module arguments correctly

2009-04-05 Thread Kent Johnson
On Sun, Apr 5, 2009 at 4:54 PM, Benjamin Serrato
 wrote:
> Please tell me why this code fails. I am new and I don't understand why my
> formatting of my zip arguments is incorrect. Since I am unsure how to
> communicate best so I will show the code, the error message, and what I
> believe is happening.
>
> #!c:\python30
> # Filename: backup_ver5.py
>
> import os
> import time
>
> import zipfile
>
>
> source = r'C:\Documents and Settings\Benjamin Serrato\My
> Documents\python\backup_list'
>
> target_dir = r'C:\Documents and Settings\Benjamin Serrato\My
> Documents\python\backup_dir'
>
>
> today = target_dir + os.sep + time.strftime('%Y%m%d')
>
> now = time.strftime('%H%M%S')
>
> comment = input('Enter a comment --> ')
>
> if len(comment) == 0:
>   target = today + os.sep + now + '.zip'
>
> else:
>   target = today + os.sep + now + '_' + \
>   comment.replace(' ', '_') + '.zip'
>
> if not os.path.exists(today):
>   os.mkdir(today)
>   print('Successfully created directory', today)
>
>
>
> print(target)
> print(source)
> zip_command = zipfile.ZipFile(target, 'w').write(source)

The argument to write() must be a file path,  are you giving it a
directory path?
>
> if os.system(zip_command) == 0:
>   print('Successful backup to', target)
> else:
>   print('Backup FAILED')
>
>
> I receive this error message:
>   File "c:\python30\lib\zipfile.py", line 1031, in write
>     fp = io.open(filename, "rb")
>   File "C:\Python30\lib\io.py", line 222, in open
>     closefd)
>   File "C:\Python30\lib\io.py", line 615, in __init__
>     _fileio._FileIO.__init__(self, name, mode, closefd)
> IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\\Benjamin
> Ser
> rato\\My Documents\\python\\backup_list'

Notice that it is the write() call that is failing, not ZipFile(), and
the error is a read error on target.

> The two print tests before zip_command is assigned tell me that the two
> strings are being passed to zipfile.ZipFile() correctly. The traceback tells
> me I am not calling zipfile.ZipFile() correctly. The error in __init__ makes
> me more sure of this.

No, it is FileIO.__init__() that is failing, not ZipFile.__init__()

> I used this site to figure out how to use zipfile. zipfile is a class, I
> import it at the start of the program then I use it and its primary method.
> I pass the file I would like to write to zipfile.ZipFile('file to write',
> 'mode') and set the program to open an object set to be writable. Then the
> command writes the file to the destination folder with a sub-method like so,
> "".zipfile('files to write').

It should be zipfile('file to write')

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


Re: [Tutor] Formatting zip module arguments correctly

2009-04-05 Thread bob gailer

Benjamin Serrato wrote:
> Please tell me why this code fails. I am new and I don't understand 
why my formatting of my zip arguments is incorrect. Since I am unsure 
how to communicate best so I will show the code, the error message, and 
what I believe is happening.

>
> #!c:\python30
> # Filename: backup_ver5.py
>
> import os
> import time
>
> import zipfile
>
>
> source = r'C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_list'

>
> target_dir = r'C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_dir'

>
>
> today = target_dir + os.sep + time.strftime('%Y%m%d')
>
> now = time.strftime('%H%M%S')
>
> comment = input('Enter a comment --> ')
>
> if len(comment) == 0:
> target = today + os.sep + now + '.zip'
>
> else:
> target = today + os.sep + now + '_' + \
> comment.replace(' ', '_') + '.zip'
>
> if not os.path.exists(today):
> os.mkdir(today)
> print('Successfully created directory', today)
>
>
>
> print(target)
> print(source)
> zip_command = zipfile.ZipFile(target, 'w').write(source)
>
> if os.system(zip_command) == 0:
> print('Successful backup to', target)
> else:
> print('Backup FAILED')
>
>
> I receive this error message:
>
> Enter a comment -->
> C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_dir\200904

> 05\154956.zip
> C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_list

> Traceback (most recent call last):
>   File "C:\Documents and Settings\Benjamin Serrato\My 
Documents\python\backup_ve

> r5.py", line 32, in 
> zip_command = zipfile.ZipFile(target, 'w').write(source)
>   File "c:\python30\lib\zipfile.py", line 1031, in write
> fp = io.open(filename, "rb")
>   File "C:\Python30\lib\io.py", line 222, in open
> closefd)
>   File "C:\Python30\lib\io.py", line 615, in __init__
> _fileio._FileIO.__init__(self, name, mode, closefd)
> IOError: [Errno 13] Permission denied: 'C:\\Documents and 
Settings\\Benjamin Ser

> rato\\My Documents\\python\\backup_list'

Permission denied? How is that not clear?

Why it is denied has nothing to do with Python or zipfile. It is a file 
system problem. Appears you don't have permission to write to 
C:\\Documents and Settings\\Benjamin Serrato\\My Documents\\python\\


>
> The two print tests before zip_command is assigned tell me that the 
two strings are being passed to zipfile.ZipFile() correctly. The 
traceback tells me I am not calling zipfile.ZipFile() correctly. The 
error in __init__ makes me more sure of this. Last, the problem seems to 
be that I am causing my path string to have double backslashes. I can't 
follow why the IOError shows that.


Python displays \ as \\ since \ is used as an escape character. There is 
really just one \ in the actual string.


>
> I used this site to figure out how to use zipfile. zipfile is a 
class, I import it at the start of the program then I use it and its 
primary method. I pass the file I would like to write to 
zipfile.ZipFile('file to write', 'mode') and set the program to open an 
object set to be writable. Then the command writes the file to the 
destination folder with a sub-method like so, "".zipfile('files to write').

>
> Where am I going wrong?

First problem is posting in anything other than plain text. Please 
always use plain text. I hate having to get out my magnifying glass.




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


[Tutor] Formatting zip module arguments correctly

2009-04-05 Thread Benjamin Serrato
Please tell me why this code fails. I am new and I don't understand why my
formatting of my zip arguments is incorrect. Since I am unsure how to
communicate best so I will show the code, the error message, and what I
believe is happening.

#!c:\python30
# Filename: backup_ver5.py

import os
import time
import zipfile


source = r'C:\Documents and Settings\Benjamin Serrato\My
Documents\python\backup_list'

target_dir = r'C:\Documents and Settings\Benjamin Serrato\My
Documents\python\backup_dir'

today = target_dir + os.sep + time.strftime('%Y%m%d')

now = time.strftime('%H%M%S')

comment = input('Enter a comment --> ')

if len(comment) == 0:
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'

if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)


print(target)
print(source)
zip_command = zipfile.ZipFile(target, 'w').write(source)

if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')

I receive this error message:

Enter a comment -->
C:\Documents and Settings\Benjamin Serrato\My
Documents\python\backup_dir\200904
05\154956.zip
C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list
Traceback (most recent call last):
  File "C:\Documents and Settings\Benjamin Serrato\My
Documents\python\backup_ve
r5.py", line 32, in 
zip_command = zipfile.ZipFile(target, 'w').write(source)
  File "c:\python30\lib\zipfile.py", line 1031, in write
fp = io.open(filename, "rb")
  File "C:\Python30\lib\io.py", line 222, in open
closefd)
  File "C:\Python30\lib\io.py", line 615, in __init__
_fileio._FileIO.__init__(self, name, mode, closefd)
IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\\Benjamin
Ser
rato\\My Documents\\python\\backup_list'

The two print tests before zip_command is assigned tell me that the two
strings are being passed to zipfile.ZipFile() correctly. The traceback tells
me I am not calling zipfile.ZipFile() correctly. The error in __init__ makes
me more sure of this. Last, the problem seems to be that I am causing my
path string to have double backslashes. I can't follow why the IOError shows
that.

I used this site  to
figure out how to use zipfile. zipfile is a class, I import it at the start
of the program then I use it and its primary method. I pass the file I would
like to write to zipfile.ZipFile('file to write', 'mode') and set the
program to open an object set to be writable. Then the command writes the
file to the destination folder with a sub-method like so, "".zipfile('files
to write').

Where am I going wrong?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Formatting

2009-02-25 Thread prasad rao
hi
 for license in licenses:
  m = licenseRe.search(license)
  print m.group(1, 2)


('ABTA', 'No.56542')
('ATOL', None)
('IATA', None)
('ITMA', None)
Yes It is working
Thank you
Prasad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting

2009-02-24 Thread Senthil Kumaran
On Wed, Feb 25, 2009 at 10:37 AM, prasad rao  wrote:
>
> licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?')

Change that to:

licenseRe = re.compile(r'\(([A-Z]+)\)\s*(No.\d+)?')

It now works.


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


[Tutor] Formatting

2009-02-24 Thread prasad rao
hi.

s = 'Association of British Travel Agents (ABTA) No.56542\nAir Travel
Organisation Licence (ATOL)\nAppointed Agents ofIATA (IATA)\nIncentive
Travel & Meet. Association (ITMA)'


licenses = re.split("\n+", s)

licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?')


>>> for license in licenses:
   m = licenseRe.search(license)
   print m.group(1, 3)


('ABTA', None)
('ATOL', None)
('IATA', None)
('ITMA', None)

The no 56542 is not getting into  m.group()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting timedelta objects

2007-12-10 Thread wesley chun
>This is probably something simple but I can't seem to find a way to
> format a timedelta object for printing? I need to be able to print it in
> a HH:MM:SS format but without the microseconds part (which is what you
> get if you str() it).


hi noufal,

there's no real easy way to do this since only date, datetime, and
time objects in datetime have strftime() methods.  timedelta objects
only give you days, seconds, and microseconds, so you have to roll
your own:

>>> z # some random timedelta object
datetime.timedelta(1, 84830, 429624)
>>> str(z)
'1 day, 23:33:50.429624'
>>> sec = z.days*24*60*60+z.seconds
>>> min, sec = divmod(sec, 60)
>>> hrs, min = divmod(min, 60)
>>> hrs, min, sec
(47, 33, 50)
>>> '%02d:%02d:%02d' % (hrs, min, sec)
'47:33:50'

if you want to round with microseconds, you'll have to add that to the
mix above.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.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] Formatting timedelta objects

2007-12-10 Thread John Fouhy
On 11/12/2007, Noufal Ibrahim <[EMAIL PROTECTED]> wrote:
> Hello everyone,
>This is probably something simple but I can't seem to find a way to
> format a timedelta object for printing? I need to be able to print it in
> a HH:MM:SS format but without the microseconds part (which is what you
> get if you str() it).
>
>Any pointers?

datetime.timedelta have 'days', 'seconds' and 'microseconds'
attributes.  You could write your own formatter using the seconds
attribute.

e.g.:

def formatTD(td):
  hours = td.seconds // 3600
  minutes = (td.seconds % 3600) // 60
  seconds = td.seconds % 60
  return '%s:%s:%s' % (hours, minutes, seconds)

HTH!

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


[Tutor] Formatting timedelta objects

2007-12-10 Thread Noufal Ibrahim
Hello everyone,
   This is probably something simple but I can't seem to find a way to 
format a timedelta object for printing? I need to be able to print it in 
a HH:MM:SS format but without the microseconds part (which is what you 
get if you str() it).

   Any pointers?

Thanks.


-- 
~noufal
http://nibrahim.net.in/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting output into columns

2007-08-31 Thread Scott Oertel
Luke Paireepinart wrote:
> Scott Oertel wrote:
>> Someone asked me this question the other day, and I couldn't think of
>> any easy way of printing the output besides what I came up with pasted
>> below.
>>
>> So what you have is a file with words in it as such:
>>
>> apple
>> john
>> bean
>> joke
>> ample
>> python
>> nice
>>
>> and you want to sort and output the text into columns as such:
>>
>> a  p   j b  n
>> apple  python john   bean   nice
>> ample  joke
>>
>> and this is what works, but I would also like to know how to wrap the
>> columns, plus any ideas on a better way to accomplish this.
>>
>> #!/usr/bin/env python
>>
>> data = {}
>> lrgColumn = 0
>>
>> for line in open("test.txt","r").read().splitlines():
>>   
> you can just directly do
> for line in open('test.txt'):
>
> depending on your Python version.  I believe it's 2.3+.
> I have 2.4 and it works there, at least.
> If using an older version of Python, you can use .readlines() instead
> of .read().splitlines()
>
> I believe Kent and Alan already helped you with your original question.
> -Luke

The reason I use read().splitlines, is because if you do .readlines() it
adds the carriage return to the end of each line where in i have to
.rstrip() to remove it. If you use .read() it doesn't split the lines in
the file into a tuple, there for you it is not an iteration.


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


Re: [Tutor] Formatting output into columns

2007-08-30 Thread Luke Paireepinart
Scott Oertel wrote:
> Someone asked me this question the other day, and I couldn't think of
> any easy way of printing the output besides what I came up with pasted
> below.
>
> So what you have is a file with words in it as such:
>
> apple
> john
> bean
> joke
> ample
> python
> nice
>
> and you want to sort and output the text into columns as such:
>
> a  p   j b  n
> apple  python john   bean   nice
> ample  joke
>
> and this is what works, but I would also like to know how to wrap the
> columns, plus any ideas on a better way to accomplish this.
>
> #!/usr/bin/env python
>
> data = {}
> lrgColumn = 0
>
> for line in open("test.txt","r").read().splitlines():
>   
you can just directly do
for line in open('test.txt'):

depending on your Python version.  I believe it's 2.3+.
I have 2.4 and it works there, at least.
If using an older version of Python, you can use .readlines() instead of 
.read().splitlines()

I believe Kent and Alan already helped you with your original question.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Formatting output into columns

2007-08-30 Thread Kent Johnson
Alan Gauld wrote:
> "Scott Oertel" <[EMAIL PROTECTED]> wrote
>> Do you have any good documentation that could shed some more light 
>> on
>> exactly how to use format strings in such a way?
> 
> The docs contain the basic documentation

http://docs.python.org/lib/typesseq-strings.html

> # there's a slightly better way to do this which I can't recall right 
> now!
> # %% -> literal %,
> # %s = insert string
> # so %%%ss -> %Xs where X is the inserted data
> fmtStr = "%%%ss\t%%%ss%%%ss" % (max_width, max_width, max_width)
> 
> print fmtStr % tuple(data)

I think you are looking for * as a width specifier which takes the width 
from the argument list though it might be a bit awkward in this case 
where the length of the argument list varies.

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


Re: [Tutor] Formatting output into columns

2007-08-30 Thread Alan Gauld

"Scott Oertel" <[EMAIL PROTECTED]> wrote

>> Use format strings. You can calculate the column widths by 
>> analyzing
>> the data then create a format string for the required number of
>> columns.
>> Finally insert the data on each row from a tuple.
>>
> Do you have any good documentation that could shed some more light 
> on
> exactly how to use format strings in such a way?

The docs contain the basic documentation, here is a short example:


data = ['one','fifteen',''four']

max_width = max([len(w) for w in data)])

# there's a slightly better way to do this which I can't recall right 
now!
# %% -> literal %,
# %s = insert string
# so %%%ss -> %Xs where X is the inserted data
fmtStr = "%%%ss\t%%%ss%%%ss" % (max_width, max_width, max_width)

print fmtStr % tuple(data)

That should produce a format string where each column is the max width
of any of the data items

You can use the string center() method to pad the headings if 
required.
You can either put left/right justification into the format string 
(using +/-)
or use the string methods (rjust,ljust) to do it for you.

If its not clear how to extend that to a multi dimensional set of
data then feel free to ask for more detail with some sample data
and the specific requirements

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


Re: [Tutor] Formatting output into columns

2007-08-30 Thread Kent Johnson
Scott Oertel wrote:
> #!/usr/bin/env python
> 
> data = {}
> lrgColumn = 0
> 
> for line in open("test.txt","r").read().splitlines():
> char = line[0].lower()
> if not char in data:
> data[char] = [line]
> else:
> data[char].append(line)

I like
   data.setdefault(char, []).append(line)
instead of the four lines above.

> 
> for item in data:
> print item.ljust(10),
> if len(data[item]) > lrgColumn:
> lrgColumn = len(data[item])
> print
> 
> for item in range(lrgColumn):
> for i in data.iteritems():
> try:
> print i[1][item].ljust(10),

If you used data.itervalues() then it would be just
   print i[item].ljust(10),

> except IndexError:
> print "".ljust(10),
> print

To get the data in row order you can use
   map(None, *data.values())
This will give a list of rows with None in the blank spots.

You might like one of these recipes for the actual table output:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519618

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


Re: [Tutor] Formatting output into columns

2007-08-30 Thread Scott Oertel
Alan Gauld wrote:
> "Scott Oertel" <[EMAIL PROTECTED]> wrote
>
>   
>> and you want to sort and output the text into columns as such:
>>
>> a  p   j b  n
>> apple  python john   bean   nice
>> ample  joke
>>
>> and this is what works, but I would also like to know how to wrap 
>> the
>> columns, plus any ideas on a better way to accomplish this.
>> 
>
> Use format strings. You can calculate the column widths by analyzing
> the data then create a format string for the required number of 
> columns.
> Finally insert the data on each row from a tuple.
>
>
> HTH,
>
>
>   
Do you have any good documentation that could shed some more light on
exactly how to use format strings in such a way?


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


Re: [Tutor] Formatting output into columns

2007-08-30 Thread Alan Gauld

"Scott Oertel" <[EMAIL PROTECTED]> wrote

> and you want to sort and output the text into columns as such:
>
> a  p   j b  n
> apple  python john   bean   nice
> ample  joke
>
> and this is what works, but I would also like to know how to wrap 
> the
> columns, plus any ideas on a better way to accomplish this.

Use format strings. You can calculate the column widths by analyzing
the data then create a format string for the required number of 
columns.
Finally insert the data on each row from a tuple.


HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


[Tutor] Formatting output into columns

2007-08-30 Thread Scott Oertel
Someone asked me this question the other day, and I couldn't think of
any easy way of printing the output besides what I came up with pasted
below.

So what you have is a file with words in it as such:

apple
john
bean
joke
ample
python
nice

and you want to sort and output the text into columns as such:

a  p   j b  n
apple  python john   bean   nice
ample  joke

and this is what works, but I would also like to know how to wrap the
columns, plus any ideas on a better way to accomplish this.

#!/usr/bin/env python

data = {}
lrgColumn = 0

for line in open("test.txt","r").read().splitlines():
char = line[0].lower()
if not char in data:
data[char] = [line]
else:
data[char].append(line)

for item in data:
print item.ljust(10),
if len(data[item]) > lrgColumn:
lrgColumn = len(data[item])
print

for item in range(lrgColumn):
for i in data.iteritems():
try:
print i[1][item].ljust(10),
except IndexError:
print "".ljust(10),
print

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