Re: [Tutor] printing items form list

2017-03-03 Thread David Rock

> On Mar 3, 2017, at 13:42, dirkjso...@gmail.com  wrote:
> 
> On 03/03/2017 12:19 PM, Alan Gauld via Tutor wrote:
>> 
>> That's one reason why join() is a better solution, it
>> handles all of that for you. It's also faster, although
>> in a small application you'd never notice the difference.
>> 
> The ','.join(suitcase) is obviously best of all, but if one doesn't know that 
> method, the below suggestion can be fixed with:
> 
> suitcase = ['book', 'towel', 'shirt', 'pants']
> 
> for i in suitcase:
>st = st + i + ', '
> 
> print('You have a s% in your luggage.' % st)

There are three issues with that statement.
1. not knowing a method is not an excuse.  It’s worth knowing join because it 
has a lot of flexibility (and it _is_ known because of this discussion)
2. Your code as written doesn’t work because st is not defined before you use it

>>> suitcase = ['book', 'towel', 'shirt', 'pants']
>>> for i in suitcase:
... st = st + i + ', '
...
Traceback (most recent call last):
  File "", line 2, in 
NameError: name 'st' is not defined

3. Your [fixed] code (added st = ‘') and join do NOT do the same thing (note 
the extra comma and space at the end of yours)
  join: You have a book, towel, shirt, pants in your luggage.
  yours: You have a book, towel, shirt, pants,  in your luggage.


String concatenation with a loop is notorious for adding extra stuff at the 
end.  To get it right, you have to take into account what to do at the end of 
the list, which adds code complexity.

—
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] printing items form list

2017-03-03 Thread dirkjso...@gmail.com

On 03/03/2017 12:19 PM, Alan Gauld via Tutor wrote:

On 03/03/17 18:52, Peter Otten wrote:

Antonio Zagheni via Tutor wrote:


suitcase = ["book, ", "towel, ", "shirt, ", "pants"]

Hm, looks like you opened Rafael's suitcase while he wasn't looking, and
sneaked in some commas and spaces ;)

That's cheating...

Its also very difficult to maintain since if you add
new items to the suitcase you need to make sure they
all have commas except the last one. And inconsistent data formatting in
a list is a nightmare.

For example, what happens if you decide to sort the list,
the last item is no longer last and the commas are all
messed up.

That's one reason why join() is a better solution, it
handles all of that for you. It's also faster, although
in a small application you'd never notice the difference.

The ','.join(suitcase) is obviously best of all, but if one doesn't know 
that method, the below suggestion can be fixed with:


suitcase = ['book', 'towel', 'shirt', 'pants']

for i in suitcase:
st = st + i + ', '

print('You have a s% in your luggage.' % st)


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


Re: [Tutor] printing items form list

2017-03-03 Thread Alan Gauld via Tutor
On 03/03/17 18:52, Peter Otten wrote:
> Antonio Zagheni via Tutor wrote:
> 
>> suitcase = ["book, ", "towel, ", "shirt, ", "pants"] 
> 
> Hm, looks like you opened Rafael's suitcase while he wasn't looking, and 
> sneaked in some commas and spaces ;) 
> 
> That's cheating...

Its also very difficult to maintain since if you add
new items to the suitcase you need to make sure they
all have commas except the last one. And inconsistent data formatting in
a list is a nightmare.

For example, what happens if you decide to sort the list,
the last item is no longer last and the commas are all
messed up.

That's one reason why join() is a better solution, it
handles all of that for you. It's also faster, although
in a small application you'd never notice the difference.

-- 
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] printing items form list

2017-03-03 Thread David Rock

> On Mar 3, 2017, at 12:52, Peter Otten <__pete...@web.de> wrote:
> 
> Antonio Zagheni via Tutor wrote:
> 
>> suitcase = ["book, ", "towel, ", "shirt, ", "pants"]
> 
> Hm, looks like you opened Rafael's suitcase while he wasn't looking, and
> sneaked in some commas and spaces ;)
> 
> That's cheating...

yeah, just a little. :-)

You can use join for this:

suitcase = ["book", "towel", "shirt", "pants"]
output = ', '.join(suitcase)
print ("You have a %s in your luggage.") %output


—
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] printing items form list

2017-03-03 Thread Peter Otten
Antonio Zagheni via Tutor wrote:

> suitcase = ["book, ", "towel, ", "shirt, ", "pants"] 

Hm, looks like you opened Rafael's suitcase while he wasn't looking, and 
sneaked in some commas and spaces ;) 

That's cheating...

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


Re: [Tutor] printing items form list

2017-03-03 Thread Antonio Zagheni via Tutor
Hello Rafael,
I believe you are a beginner...
That is another way to do 
this...-
suitcase = ["book, ", "towel, ", "shirt, ", "pants"]
st = ''

for i in suitcase:
    
    st = st + i
    
print ("You have a %s in your luggage.") %st

Best regards...
Antonio Zagheni.

  From: "tutor-requ...@python.org" 
 To: tutor@python.org 
 Sent: Friday, March 3, 2017 2:00 PM
 Subject: Tutor Digest, Vol 157, Issue 8
   
Send Tutor mailing list submissions to
    tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
    https://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
    tutor-requ...@python.org

You can reach the person managing the list at
    tutor-ow...@python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

  1. printing items form list (Rafael Knuth)
  2. Re: printing items form list (Peter Otten)


--

Message: 1
Date: Fri, 3 Mar 2017 13:12:23 +0100
From: Rafael Knuth 
To: "Tutor@python.org" 
Subject: [Tutor] printing items form list
Message-ID:
    
Content-Type: text/plain; charset=UTF-8

I want to print individual items from a list like this:

You have a book, towel, shirt, pants in your luggage.

This is my code:

suitcase = ["book", "towel", "shirt", "pants"]
print ("You have a %s in your luggage." % suitcase)

Instead of printing out the items on the list, my code appends the
list to the string. How do I need to modify my code?

== RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py ==
You have a ['book', 'towel', 'shirt', 'pants'] in your luggage.


--

Message: 2
Date: Fri, 03 Mar 2017 13:30:23 +0100
From: Peter Otten <__pete...@web.de>
To: tutor@python.org
Subject: Re: [Tutor] printing items form list
Message-ID: 
Content-Type: text/plain; charset="ISO-8859-1"

Rafael Knuth wrote:

> I want to print individual items from a list like this:
> 
> You have a book, towel, shirt, pants in your luggage.
> 
> This is my code:
> 
> suitcase = ["book", "towel", "shirt", "pants"]
> print ("You have a %s in your luggage." % suitcase)
> 
> Instead of printing out the items on the list, my code appends the
> list to the string. How do I need to modify my code?

Have a look at the str.join() method:

>>> suitcase = ["book", "towel", "shirt", "pants"]
>>> print("You have a %s in your luggage." % ", ".join(suitcase))
You have a book, towel, shirt, pants in your luggage.

See <https://docs.python.org/3.6/library/stdtypes.html#str.join>




--

Subject: Digest Footer

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


--

End of Tutor Digest, Vol 157, Issue 8
*


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


Re: [Tutor] printing items form list

2017-03-03 Thread Mats Wichmann
On 03/03/2017 05:12 AM, Rafael Knuth wrote:
> I want to print individual items from a list like this:
> 
> You have a book, towel, shirt, pants in your luggage.
> 
> This is my code:
> 
> suitcase = ["book", "towel", "shirt", "pants"]
> print ("You have a %s in your luggage." % suitcase)
> 
> Instead of printing out the items on the list, my code appends the
> list to the string. How do I need to modify my code?
> 
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py ==
> You have a ['book', 'towel', 'shirt', 'pants'] in your luggage.


By way of explanation:

suitcase = ["book", "towel", "shirt", "pants"]
print(type(suitcase))
print ("You have a %s in your luggage." % suitcase)


===

You have a ['book', 'towel', 'shirt', 'pants'] in your luggage.

suitcase is a list.  You explicitly ask for it to be shown a string with
"%s", so the list class's string representation method is called to
produce what the class thinks is the best way to show what the list
contents looks like.  that conversion to a string someone else's idea
(Python default), but not what you wanted, though; joining with commas
is the right choice based on what you said you wanted.


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


Re: [Tutor] printing items form list

2017-03-03 Thread Peter Otten
Rafael Knuth wrote:

> I want to print individual items from a list like this:
> 
> You have a book, towel, shirt, pants in your luggage.
> 
> This is my code:
> 
> suitcase = ["book", "towel", "shirt", "pants"]
> print ("You have a %s in your luggage." % suitcase)
> 
> Instead of printing out the items on the list, my code appends the
> list to the string. How do I need to modify my code?

Have a look at the str.join() method:

>>> suitcase = ["book", "towel", "shirt", "pants"]
>>> print("You have a %s in your luggage." % ", ".join(suitcase))
You have a book, towel, shirt, pants in your luggage.

See 


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


Re: [Tutor] printing all text that begins with "25"

2014-10-02 Thread Martin A. Brown


Hi Bo,

I am trying to write a python script that will run the above 
command and only print out the IP's that begin with 25. How do I 
strip out all other text except for the IP's that begin with "25?"


I liked the suggestion by John Doe earlier that this is a pretty 
good case for 'grep', but perhaps you want to do more than simply 
see the results on the terminal.


So, you seem to want to be able to 'grep' for IPs that match a 
particular prefix, 25.0.0.0/8.  Do you, perchance work for


  org-name:   DINSA, Ministry of Defence [0]

or are you using 25.0.0.0/8 in a private network.  If the latter, 
are you sure you don't want to use one of the RFC 1918 networks?


Would it be best to send to a file first, then read the contents 
of the file? Would I need to use regex?


Others have addressed some of this.

I know how to run the above command in python. I also know how to 
send the output to a file and read the file; however I cannot 
figure out how to strip all text out except for the IPs that begin 
with "25."


Ok, so I can't help but observe that you are working with 
IP-oriented data.  While you can perform tests like:


  ipstr.startswith('25')  # -- yep, '250', '251', '253', '254', also

or similar tests by writing a regular expression and using one of 
the heavier tools (re.findall, re.compile, re.match), I think that 
merely helps you locate the text that you think is the IP address.


If you are asking is the IP within the 25.0.0.0/8 prefix, then you 
probably want to use the ipaddr (Python 2.x from PyPI) or ipaddress 
(Python 3.x stdlib) module to validate the IP and make sure that the 
IP is in a prefix of interest.


I made one liberal change to the format of your data--I made it 
tab-separated.  If it is not tab-separated, then you can see which 
line would probably need to have your regex line-splitter.


The below, is more general than finding every IP that starts with 
'25.', because now you can "ipaddr-grep" for what you want.


  #! /usr/bin/python

  from __future__ import print_function

  import sys
  try:  # -- Python2.x
  import ipaddr as ipaddress
  except ImportError:  # -- Python3.x
  import ipaddress

  separator = '\t'

  def ipaddr_grep(prefix, fin):
  for line in fin:
  line = line.strip()
  if not line or line.startswith('#'):
  continue
  parts = line.strip().split(separator) # -- tab separated
  ip = ipaddress.IPv4Address(parts[2])
  if ip in prefix:
  yield(line)

  def ipaddr_grep_main(prefix, fnames):
  prefix = ipaddress.IPv4Network(prefix)
  while fnames:
  fname = fnames.pop()
  with open(fname) as fin:
  for line in ipaddr_grep(prefix, fin):
  print(line)

   if __name__ == '__main__':
   ipaddr_grep_main(sys.argv[1], sys.argv[2:])

I happen to be the sort of person who always wants to point out the 
IP-related tools available in Python hence my reply to your post.


Happy trails and good luck,

-Martin

 [0] 
https://apps.db.ripe.net/search/query.html?searchtext=25.0.0.0/8&source=RIPE#resultsAnchor

--
Martin A. Brown
http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing all text that begins with "25"

2014-10-02 Thread Alan Gauld

On 02/10/14 16:41, Bo Morris wrote:


of the following output

087-888-279   Pandora25.x.x.xxx   alias: not
set

096-779-867   AM1LaptopBD-PC25.x.x.xxx   alias: not set


097-552-220   OWS-Desktop 125.0.0.0  alias: not set

099-213-641   DESKTOP 25.0.0.0  alias: not
set

I am trying to write a python script that will run the above command and
only print out the IP's that begin with 25. How do I strip out all other
text except for the IP's that begin with "25?"


Use split() to get the 'columns' in a list then use strip() to get rid 
of whitespace.



HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] printing all text that begins with "25"

2014-10-02 Thread John Doe
Hello,

If you want to accomplish what you are looking for within linux
(perhaps a bash script, instead?):

$ hamachi list | grep -oP '25\.\d+\.\d+\.\d+'
25.0.0.0
25.255.255.255

For your python script, you want to group your regex:
reg = re.compile(r'(25\.\d+\.\d+\.\d+)', re.MULTILINE)

So when you call group(1) or group(0), it'll grab just the addresses.


On Thu, Oct 2, 2014 at 12:33 PM, David Rock  wrote:
> * Bo Morris  [2014-10-02 11:41]:
>> Hello all, hope everyone is doing well.
>>
>> When I run the linux command "hamachi list" i get something along the lines
>> of the following output
>>
>>087-888-279   Pandora25.x.x.xxx   alias: not 
>> set
>>096-779-867   AM1LaptopBD-PC25.x.x.xxx   alias: not set
>>097-552-220   OWS-Desktop 125.0.0.0  alias: not set
>>099-213-641   DESKTOP 25.0.0.0  alias: not set
>>
>> I am trying to write a python script that will run the above command and
>> only print out the IP's that begin with 25. How do I strip out all other
>> text except for the IP's that begin with "25?"
>
> There are a few assumptions that need to be made, for starters.
>
> Is the format always the same (ie, is the IP address always in column 3
> separated by whitespace)?  Looking at the line with "OWS-Desktop 1", the
> answer is no.  That complicates things a bit.  If it was true, you could
> use the string split method to get column 3.  Maybe the fields are
> separated by a tab?
>
> A regex may be possible, but you will have similar issues to using
> split.
>
> I'm also assuming it's possible for there to be IP addresses that do not
> start with 25. Are you looking to isolate those?
>
> It's not necessary to write out to a file first.  You can get the output
> from commands and work on it directly.
>
> Another approach would be to change the command you are running.  I've
> never heard of hamachi list before; does it have any commandline options
> to display only IP addresses?
>
> --
> 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] printing all text that begins with "25"

2014-10-02 Thread Sebastian Silva



El jue, 2 de oct 2014 a las 11:33 AM, David Rock  
escribió:


A regex may be possible, but you will have similar issues to using
split.


In my humble experience, a regex is the way to go:

import re
ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', s )

you will get a list of IP addresses and can filter from there which 
ones start with "25."
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing all text that begins with 25"

2014-10-02 Thread Crush
Yes the format is always the same and the IPs will always be in the 3rd 
collumn; although, the amount of whitspace that seperates column 2 and 3 may be 
different depending on how long the name is in column 2. Also all of the IPs 
will begin with a "25," so there would be no fear of having to deal with other 
IP addresses that start with anything else. 

Hamachi is VPN software and unfortunately, there is no command line argument 
that allows one to isolate the IPs. 

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


Re: [Tutor] printing all text that begins with "25"

2014-10-02 Thread David Rock
* Bo Morris  [2014-10-02 11:41]:
> Hello all, hope everyone is doing well.
> 
> When I run the linux command "hamachi list" i get something along the lines
> of the following output
> 
>087-888-279   Pandora25.x.x.xxx   alias: not 
> set
>096-779-867   AM1LaptopBD-PC25.x.x.xxx   alias: not set
>097-552-220   OWS-Desktop 125.0.0.0  alias: not set
>099-213-641   DESKTOP 25.0.0.0  alias: not set
> 
> I am trying to write a python script that will run the above command and
> only print out the IP's that begin with 25. How do I strip out all other
> text except for the IP's that begin with "25?"

There are a few assumptions that need to be made, for starters.

Is the format always the same (ie, is the IP address always in column 3
separated by whitespace)?  Looking at the line with "OWS-Desktop 1", the
answer is no.  That complicates things a bit.  If it was true, you could
use the string split method to get column 3.  Maybe the fields are
separated by a tab?

A regex may be possible, but you will have similar issues to using
split.  

I'm also assuming it's possible for there to be IP addresses that do not
start with 25. Are you looking to isolate those?

It's not necessary to write out to a file first.  You can get the output
from commands and work on it directly.

Another approach would be to change the command you are running.  I've
never heard of hamachi list before; does it have any commandline options
to display only IP addresses?

-- 
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] printing all text that begins with "25"

2014-10-02 Thread Dave Angel
Bo Morris  Wrote in message:

(Thanks for starting a new thread when asking a new question.  But
 please use text mode in your emails, not html.)

For the first version,  write it as a filter, and pipe the two
 commands together in the shell. So all you have to do is read a
 line from stdin, parse it, and conditionally write it to
 std.

You don't provide a spec, just a short sample of data. So I'll
 have to guess that the leading whitespace is irrelevant and the
 first two fields cannot contain whitespace, and that each contain
 at least one non-whitespace character.  Further that the fields
 are delimited by whitespace. 

So, use lstrip to get rid of leading junk, and split to split the
 line into fields. Then subscript into the resulting list to get
 the appropriate field. And use startswith to check the desired 3
 character string.  Notice that you don't just want to use "25",
 or you might accept an ip like 251.12.3.6

That still leaves you to deal with reporting invalid files, such
 as those with short or blank lines.

-- 
DaveA

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


Re: [Tutor] Printing a list count - Help

2014-08-30 Thread boB Stepp
On Fri, Aug 29, 2014 at 2:17 PM, Derek Jenkins  wrote:
> Hi everybody,
>
> I have a list that I want to go through and finally print a total
> count of particular items. In this case, I want to print the result of
> how many A's and B's are in the list.
>
> honor_roll_count = 0
> student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"]
>
> for grades in student_grades:
> honor_roll_count = honor_roll_count + 1
> if grades == "A" or grades == "B":
> print honor_roll_count
>

Are you sure you have your increment of honor_roll_count where you
want it? As it is placed you are counting how many grades of any kind
there are.

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


Re: [Tutor] Printing a list count - Help

2014-08-29 Thread Alan Gauld

On 29/08/14 20:17, Derek Jenkins wrote:

Hi everybody,

I have a list that I want to go through and finally print a total
count of particular items. In this case, I want to print the result of
how many A's and B's are in the list.

honor_roll_count = 0
student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"]

for grades in student_grades:
 honor_roll_count = honor_roll_count + 1
 if grades == "A" or grades == "B":
 print honor_roll_count



lists have a count() method.
try this:

honor_roll_count = student_grades.count('A') + student_grades.count('B')

For more complex data sets you could use the itertools groupby function too.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Printing a list count - Help

2014-08-29 Thread Derek Jenkins
Alex,

Thanks for taking this one step further! I do appreciate it... +1

On Fri, Aug 29, 2014 at 3:48 PM, Alex Kleider  wrote:
> On 2014-08-29 12:17, Derek Jenkins wrote:
>>
>> Hi everybody,
>>
>> I have a list that I want to go through and finally print a total
>> count of particular items. In this case, I want to print the result of
>> how many A's and B's are in the list.
>>
>> honor_roll_count = 0
>> student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C",
>> "A"]
>>
>> for grades in student_grades:
>> honor_roll_count = honor_roll_count + 1
>> if grades == "A" or grades == "B":
>> print honor_roll_count
>>
>> The above code prints 8 lines, each being an entry for which item in
>> the list was either A or B. Again, I'm looking for the result to be
>> the number 8 itself - the total number of instances that A or B occurs
>> in the list.
>
>
> Try the following:
> print("Running Python3 script: 'tutor.py'...")
>
>
> student_grades = ["A", "C", "B", "B", "C", "A", "F",
> "B", "B", "B", "C", "A"]
>
> grades = {}
>
> for grade in student_grades:
> grades[grade] = grades.get(grade, 0) + 1
>
> for grade in sorted(grades.keys()):
> print("'{}': {}".format(grade, grades[grade]))
>
> If you are using Python 2, I believe the get method is called something
> else; you can look it up if need be.
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing a list count - Help

2014-08-29 Thread Derek Jenkins
honor_roll_count = 0
student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"]

for grades in student_grades:
if grades == "A" or grades == "B":
honor_roll_count = honor_roll_count + 1
print honor_roll_count



That works more to my liking. Thanks a million, Danny and Bob!

On Fri, Aug 29, 2014 at 3:42 PM, boB Stepp  wrote:
> On Fri, Aug 29, 2014 at 2:17 PM, Derek Jenkins  
> wrote:
>> Hi everybody,
>>
>> I have a list that I want to go through and finally print a total
>> count of particular items. In this case, I want to print the result of
>> how many A's and B's are in the list.
>>
>> honor_roll_count = 0
>> student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"]
>>
>> for grades in student_grades:
>> honor_roll_count = honor_roll_count + 1
>> if grades == "A" or grades == "B":
>> print honor_roll_count
>>
>
> Are you sure you have your increment of honor_roll_count where you
> want it? As it is placed you are counting how many grades of any kind
> there are.
>
> --
> boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing a list count - Help

2014-08-29 Thread Danny Yoo
>
> The above code prints 8 lines, each being an entry for which item in
> the list was either A or B. Again, I'm looking for the result to be
> the number 8 itself - the total number of instances that A or B occurs
> in the list.


Hi Derek,

Hint: the code currently prints a variable within the loop.  But you
can print the value of your variable _outside_ the loop, after all the
student_grades have been processed.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing multi-line variables horizontally

2014-08-08 Thread Steven D'Aprano
On Fri, Aug 08, 2014 at 01:50:53AM -0700, Greg Markham wrote:
[...]
> So, how would I get this to display horizontally?
> 
> Like so...
> .-.   .-.
> | |   |o|
> |  o  |   | |
> | |   |o|
> `-'   `-'


Nice question! I recommend that you try to solve the problem yourself, 
if you can, but once you've given it a good solid try, you can have a 
look at my solution and see if you can understand it. Feel free to ask 
questions as needed.


S
P
O
I
L
E
R
 
S
P
A
C
E

.
.
.

N
O
 
C
H
E
A
T
I
N
G


def expand(rows, width, height):
"""Expand a list of strings to exactly width chars and height rows.

>>> block = ["abcde",
...  "fgh",
...  "ijklmno"]
>>> result = expand(block, 8, 4)
>>> for row in result:
... print (repr(row))
...
'abcde   '
'fgh '
'ijklmno '
''

"""
if len(rows) > height:
raise ValueError('too many rows')
extra = ['']*(height - len(rows))
rows = rows + extra
for i, row in enumerate(rows):
if len(row) > width:
raise ValueError('row %d is too wide' % i)
rows[i] = row + ' '*(width - len(row))
return rows


def join(strings, sep="  "):
"""Join a list of strings side-by-side, returning a single string.

>>> a = '''On peut rire de tout,
... mais pas avec tout le
... monde.
... -- Pierre Desproges'''
>>> b = '''You can laugh about
... everything, but not
... with everybody.'''
>>> values = ["Quote:", a, b]
>>> print (join(values, sep=""))  #doctest:+NORMALIZE_WHITESPACE
Quote:On peut rire de tout,You can laugh about
  mais pas avec tout leeverything, but not
  monde.   with everybody.
  -- Pierre Desproges

"""
blocks = [s.split('\n') for s in strings]
h = max(len(block) for block in blocks)
for i, block in enumerate(blocks):
w = max(len(row) for row in block)
blocks[i] = expand(block, w, h)
result = []
for row in zip(*blocks):
result.append(sep.join(row))
return '\n'.join(result)



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


Re: [Tutor] Printing multi-line variables horizontally

2014-08-08 Thread emile

On 08/08/2014 10:58 AM, emile wrote:

On 08/08/2014 01:50 AM, Greg Markham wrote:



die_1 = """
.-.
| |
|  o  |
| |
`-'"""

die_2 = """
.-.
|o|
| |
|o|
`-'"""




Not quite sure how this part was dropped...

>>> for line in zip(die_1.split("\n"),die_2.split("\n")): print line
...
('', '')
('.-.', '.-.')
('| |', '|o|')
('|  o  |', '| |')
('| |', '|o|')
("`-'", "`-'")




I'll leave the cleanup as an exercise for you.

HTH,

Emile


___
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] Printing multi-line variables horizontally

2014-08-08 Thread Mark Lawrence

On 08/08/2014 18:56, Joel Goldstick wrote:

On Fri, Aug 8, 2014 at 4:50 AM, Greg Markham  wrote:

Hello,

Python novice back again.  :)  I'm making progress in my learning process,
but struggling whenever attempting to creatively go beyond what's required
in the various chapter assignments.  For example, there's a simple random
die roller program that looks like the following:


# Craps Roller
# Demonstrates random number generation

import random

# generate random numbers 1 - 6
die1 = random.randint(1, 6)
die2 = random.randrange(6) + 1

total = die1 + die2

print("You rolled a", die1, "and a", die2, "for a total of", total)

input("\n\nPress the enter key to exit.")


I wanted to make it a little more interesting by using ascii art
representations of the six die.  When printing, however, they do so
vertically and not horizontally.  Here's a snippet of the code:


die_1 = """
.-.
| |
|  o  |
| |
`-'"""

die_2 = """
.-.
|o|
| |
|o|
`-'"""

print(die_1, die_2)


So, how would I get this to display horizontally?

Like so...
.-.   .-.
| |   |o|
|  o  |   | |
| |   |o|
`-'   `-'



Does this http://code.activestate.com/recipes/473893-sudoku-solver/ help 
at all, especially the show function right at the top?




This isn't so easy because as you print the first die, your cursor
ends up at the bottom of its display.

There is a module called curses which lets you  manipulate the
terminal.  It has functions to get the x,y position on the screen, and
to set it (i. e. move the cursor).  You might want to play with that.



The Python curses module is *nix only but see this 
https://pypi.python.org/pypi/UniCurses/1.2 as an alternative for other 
platforms.


--
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] Printing multi-line variables horizontally

2014-08-08 Thread Danny Yoo
On Fri, Aug 8, 2014 at 1:50 AM, Greg Markham  wrote:
> Hello,
>
> Python novice back again.  :)  I'm making progress in my learning process,
> but struggling whenever attempting to creatively go beyond what's required
> in the various chapter assignments.  For example, there's a simple random
> die roller program that looks like the following:


Hi Greg,

It looks like each die has the same dimensions.  What I mean is that
it looks like each "die" has the same number of lines, and each line
is the same width.  Is that assumption correct?  If so, then that
might simplify matters for you.  It sounds like you're trying to build
a "row" of dice.  To do so, you might be able to loop over the lines
of both dice at once to get the composite image.

That is:

row[0] = die_1_lines[0] + die_2_lines[0]
row[1] = die_1_lines[1] + die_2_lines[1]
...

where we take horizontal slices of each dice and stick them side by
side.  To make this work, we need to be able to get at individual
lines.  To break a string into a list of lines, see

https://docs.python.org/2/library/stdtypes.html#str.splitlines
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing multi-line variables horizontally

2014-08-08 Thread Alan Gauld

On 08/08/14 09:50, Greg Markham wrote:


I wanted to make it a little more interesting by using ascii art
representations of the six die.  When printing, however, they do so
vertically and not horizontally.  Here's a snippet of the code:


die_1 = """
.-.
| |
|  o  |
| |
`-'"""


The triple quoted strings have newlines embedded in them.


print(die_1, die_2)


So, how would I get this to display horizontally?

Like so...
.-.   .-.
| |   |o|
|  o  |   | |
| |   |o|
`-'   `-'



You can split the strings and print each pair side by side separated by 
a gap. Sometjing like


die_1 = """
 .-.
 | |
 |  o  |
 | |
 `-'""".split()

etc...

separator = "   "
for index,line in enumerate(die1):
print (line + separator + die2[index])

Untested, but I hope you get the idea.

PS. Personally I'd keep the dies in a list(or dict)
so you can access die1 as dies[0] and die2 as dies[1]

The index/key is then easily determined from the
roll value.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Printing multi-line variables horizontally

2014-08-08 Thread emile

On 08/08/2014 01:50 AM, Greg Markham wrote:



die_1 = """
.-.
| |
|  o  |
| |
`-'"""

die_2 = """
.-.
|o|
| |
|o|
`-'"""



I'll leave the cleanup as an exercise for you.

HTH,

Emile


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


Re: [Tutor] Printing multi-line variables horizontally

2014-08-08 Thread Joel Goldstick
On Fri, Aug 8, 2014 at 4:50 AM, Greg Markham  wrote:
> Hello,
>
> Python novice back again.  :)  I'm making progress in my learning process,
> but struggling whenever attempting to creatively go beyond what's required
> in the various chapter assignments.  For example, there's a simple random
> die roller program that looks like the following:
>
>
> # Craps Roller
> # Demonstrates random number generation
>
> import random
>
> # generate random numbers 1 - 6
> die1 = random.randint(1, 6)
> die2 = random.randrange(6) + 1
>
> total = die1 + die2
>
> print("You rolled a", die1, "and a", die2, "for a total of", total)
>
> input("\n\nPress the enter key to exit.")
>
>
> I wanted to make it a little more interesting by using ascii art
> representations of the six die.  When printing, however, they do so
> vertically and not horizontally.  Here's a snippet of the code:
>
>
> die_1 = """
> .-.
> | |
> |  o  |
> | |
> `-'"""
>
> die_2 = """
> .-.
> |o|
> | |
> |o|
> `-'"""
>
> print(die_1, die_2)
>
>
> So, how would I get this to display horizontally?
>
> Like so...
> .-.   .-.
> | |   |o|
> |  o  |   | |
> | |   |o|
> `-'   `-'
>

This isn't so easy because as you print the first die, your cursor
ends up at the bottom of its display.

There is a module called curses which lets you  manipulate the
terminal.  It has functions to get the x,y position on the screen, and
to set it (i. e. move the cursor).  You might want to play with that.

If you want to get your feet wet with unicode, you could use the dice
characters (see: http://www.unicode.org/charts/PDF/U2600.pdf).

>>> dice_1 = '\u2680'
>>> print (dice_1)
⚀

>>> print (dice_1, dice_2)
⚀ ⚁

They are pretty small.

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



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


Re: [Tutor] Printing from python

2014-03-21 Thread Lee Harr
> is there another way to print a PDF form python?
>
> My problem is a PDF which is printed well by evince, but not with lp, 
> even not out of python using
>
> os.system("lp some_options file.pdf")
>
> Later on I have to build the PDF in a python program (using reportlab) 
> and then print it, even from the python program.


I have done this several times before -- generating a pdf with python
using reportlab and then printing the result by handing it to lpr.

(Not sure what exactly is the difference between lp and lpr, but from
   a bit of research, it looks like either one should do the job.)


The first thing you need to do is make sure that you can print
the file from your regular shell (not python) using your chosen
print command.

If that does not work, python is not going to do anything magical.

If you are having trouble with that, it is more of a question for the
mailing list supporting your chosen operating system.


Once you get that working, shelling out from python will be able
to accomplish the same task.

(The one possible gotcha is finding the correct path to the file.
   I think I tended to use full paths to everything to make sure
   that the correct things would be found.) 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing from python

2014-03-14 Thread Ben Finney
Ulrich Goebel  writes:

> So I look for a (nice documented) library which give access to the
> CUPS API or something else to print the PDF from python.
>
> Any help is welcome!

The problem isn't really one to be solved within your program, IMO.

Printing is implemented as a service at the operating system (OS) level.
Once you have a document in a form suitable for sending to a printer
(such as a PDF), the OS is where any problems with the actual printing
need to be addressed.

Also, since it is implemented at the OS level, you're not going to find
a solution in a platform-agnostic programming language like Python. The
solution, whatever it is, will be highly dependent on the services
presented by your specific OS.

Of course, once you have a suitable OS service for printing the
document, Python can send the document to that service. But at that
point, the Python code will be trivially easy: probably invoking an
external command via ‘subprocess.call’ or ‘subprocess.check_call’.

In short: printing is a problem to be solved via the OS, not via Python.

-- 
 \ “We are not gonna be great; we are not gonna be amazing; we are |
  `\   gonna be *amazingly* amazing!” —Zaphod Beeblebrox, _The |
_o__)Hitch-Hiker's Guide To The Galaxy_, Douglas Adams |
Ben Finney

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


Re: [Tutor] Printing from python

2014-03-14 Thread Alan Gauld

On 14/03/14 10:40, Ulrich Goebel wrote:


Later on I have to build the PDF in a python program (using reportlab)
and then print it, even from the python program.

So I look for a (nice documented) library which give access to the CUPS
API or something else to print the PDF from python.


I may be mistaken but I don't think CUPS will help you.

PDF documents are effectively programs that have to be interpreted
by a PDF reader of some sort. Some printers have that capability
built in, most require a program such as Acrobat or ghostscript
to do the formatting for them.

I don't think CUPS has an API for rendering PDF directly it
will simply send the PDF direct to a PDF aware printer or take
the image out from a PDF reader and send it to a standard
print driver.

Your Qt solution may support PDF rendering, I don't know Qt,
but its definitely worth pursuing. Failing that you probably
do need to use subprocess to launch ghostscript or similar.
But there is no shame in that, chaining programs together
is standard Unix practice and a sign of good design - one
program does one job.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Printing from python

2014-03-14 Thread Timo

op 14-03-14 12:14, Ulrich Goebel schreef:
I just found a hint, the Qt QPrinter Class. I use Qt, so that could be 
a solution?


This would be your best bet, use the tools which are provided. I'm a GTK 
user and use the GTK printing API to both create and print reports.


If you want to use cups, this is a project with Python bindings for 
cups: https://pypi.python.org/pypi/pycups/1.9.66


Timo




Am 14.03.2014 11:40, schrieb Ulrich Goebel:

Hallo,

is there another way to pritt a PDF form python?

My problem is a PDF which is printed well by evince, but not with lp,
even not out of python using

os.system("lp some_options file.pdf")

Later on I have to build the PDF in a python program (using reportlab)
and then print it, even from the python program.

So I look for a (nice documented) library which give access to the CUPS
API or something else to print the PDF from python.

Any help is welcome!

Ulrich






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


Re: [Tutor] Printing from python

2014-03-14 Thread Russel Winder
On Fri, 2014-03-14 at 11:40 +0100, Ulrich Goebel wrote:
> Hallo,
> 
> is there another way to pritt a PDF form python?
> 
> My problem is a PDF which is printed well by evince, but not with lp, 
> even not out of python using
> 
> os.system("lp some_options file.pdf")

Python is deprecating os.system in favour of using the subprocess
package.

subprocess.call('lp some_options file.pdf', shell=True)

or

subprocess.call(['lp', *some_options, 'file.pdf')

assuming some_options is a sequence of strings, on option per string.

> Later on I have to build the PDF in a python program (using reportlab) 
> and then print it, even from the python program.
> 
> So I look for a (nice documented) library which give access to the CUPS 
> API or something else to print the PDF from python.
> 
> Any help is welcome!

Debian Sid has packages python-cups and python-cupshelpers which are
Python 2 APIs for working with CUPS. Sadly there do not seem to be
Python 3 versions of these In Debian, but the package in PyPI is pycups
so can be made available to Pytho 3. Also: 

http://cyberelk.net/tim/software/pycups/

I have not used these yet myself, but I have trying them out on my
agenda for later in the spring.

-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder


signature.asc
Description: This is a digitally signed message part
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing from python

2014-03-14 Thread Ulrich Goebel



Am 14.03.2014 11:40, schrieb Ulrich Goebel:

is there another way to pritt a PDF form python?


sorry, that doesn't make sense. I should say: is there another way ... 
besides os.system()?



--
Ulrich Goebel
Paracelsusstr. 120, 53177 Bonn
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing from python

2014-03-14 Thread Ulrich Goebel
I just found a hint, the Qt QPrinter Class. I use Qt, so that could be a 
solution?



Am 14.03.2014 11:40, schrieb Ulrich Goebel:

Hallo,

is there another way to pritt a PDF form python?

My problem is a PDF which is printed well by evince, but not with lp,
even not out of python using

os.system("lp some_options file.pdf")

Later on I have to build the PDF in a python program (using reportlab)
and then print it, even from the python program.

So I look for a (nice documented) library which give access to the CUPS
API or something else to print the PDF from python.

Any help is welcome!

Ulrich




--
Ulrich Goebel
Paracelsusstr. 120, 53177 Bonn
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing list in a Column

2012-08-31 Thread Alan Gauld

On 31/08/12 02:12, Ashley Fowler wrote:

Can anyone help me edit this code below to return the list in the form
of a column instead of a row?

def printList():
 list1 = input("Insert a list")
 list = [list1]
 print (list)


First you need to convert the string that your user types into a list of 
individual entries. At the moment your list consists of a single string 
so the column will only have a single line.


You probably want to look at the split() method of strings.

Alternatively you could write a loop which reads each entry individually 
from the user.


HTH
--
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] Printing list in a Column

2012-08-30 Thread Mark Lawrence

On 31/08/2012 02:12, Ashley Fowler wrote:

Can anyone help me edit this code below to return the list in the form of a 
column instead of a row?





def printList():
 list1 = input("Insert a list")
 list = [list1]
 print (list)



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



Use one of the two answers that you got roughly half an hour before you 
posted this?


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Printing a list as a column

2012-08-30 Thread Mark Lawrence

On 31/08/2012 01:15, Ashley Fowler wrote:

Does anyone know how to print a list in a form of a column instead of a row?



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



This simple?

>>> mylist=range(5)
>>> for x in mylist:
... print x
...
0
1
2
3
4

--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Printing with no newline :(

2011-11-07 Thread Prasad, Ramit
>> for line in file:
>> m = re.search(regexp, line)
>> if m:
>> letterGroup = m.group(0)
>> print(letterGroup[4])

>You can specify what to print after the argument(s) with the end keyword 
>parameter:

 items = 1, 2, 3
 for item in items:
>... print(item, end=" ")
>...


Alternatively you could do the following.
letterGroups = []
for line in file:
m = re.search(regexp, line)
if m:
letterGroups.append( m.group(0)[4] )

print( ' '.join( letterGroups ) )



Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing with no newline :(

2011-11-07 Thread Sarma Tangirala
On 6 November 2011 21:09, Alan Gauld  wrote:

> On 06/11/11 10:23, Sarma Tangirala wrote:
>
>  I'm sorry. Didn't notice the python 3 part, I just joined the list and
>> did not look at the OPs post. Sorry about that.
>>
>
> welcome to the list :-)
>
>
>  Please bear with me on this, but does the following not print "end" for
>> every iteration of "items"?
>>
>> for item in items:
>>  print(item, end="")
>>
>
> No, end is a new optional parameter for the print function in Python 3.
> Recall that in Python2 print was a command whereas in Python 3 it is a
> function which has a couple of new options:
>
>
Thank you!


> ---
> Help on built-in function print in module builtins:
>
> print(...)
>print(value, ..., sep=' ', end='\n', file=sys.stdout)
>
>Prints the values to a stream, or to sys.stdout by default.
>Optional keyword arguments:
>file: a file-like object (stream); defaults to the current sys.stdout.
>sep:  string inserted between values, default a space.
>end:  string appended after the last value, default a newline.
>
>
>
> --
> 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
>




-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Alan Gauld

On 06/11/11 10:23, Sarma Tangirala wrote:


I'm sorry. Didn't notice the python 3 part, I just joined the list and
did not look at the OPs post. Sorry about that.


welcome to the list :-)


Please bear with me on this, but does the following not print "end" for
every iteration of "items"?

for item in items:
  print(item, end="")


No, end is a new optional parameter for the print function in Python 3.
Recall that in Python2 print was a command whereas in Python 3 it is a 
function which has a couple of new options:


---
Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.



--
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] Printing with no newline :(

2011-11-06 Thread Sarma Tangirala
On 6 November 2011 16:57, Dave Angel  wrote:

> On 11/06/2011 05:23 AM, Sarma Tangirala wrote:
>
>> 
>>
>
>   I just joined the list and did
>>
>
> WELCOME to the list.  I should have said that first.
>
> --
>
> DaveA
>
>
Ha! Sorry for the noise again!

-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Dave Angel

On 11/06/2011 05:23 AM, Sarma Tangirala wrote:





 I just joined the list and did


WELCOME to the list.  I should have said that first.

--

DaveA

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


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Dave Angel

On 11/06/2011 05:23 AM, Sarma Tangirala wrote:
 



python 3
.

Please bear with me on this, but does the following not print "end" for
every iteration of "items"?

for item in items:
  print(item, end="")


Sure it does.  And the value of end is the empty string.  So it prints 
nothing but the item itself.


If you don't supply an argument for 'end', it also prints end, but the 
default value, which is documented as a newline. So it prints the item 
followed by a newline.  In other words, it prints each item on a 
separate line.


--

DaveA

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


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Sarma Tangirala
I am so very sorry for the noise. I was careless in reading the OPs post.

On 6 November 2011 15:53, Sarma Tangirala  wrote:

>
>
> On 6 November 2011 15:47, Dave Angel  wrote:
>
>> On 11/06/2011 04:45 AM, Sarma Tangirala wrote:
>>
>>> On 6 November 2011 13:11, Peter Otten<__pete...@web.de>  wrote:
>>>
>>>  Joe Batt wrote:

  I am learning Python 3 and programming and am very new so please bear
>
 

  for item in items:
>>>
>> ... print(item, end="WHATEVER")


>>> Another way of writing the above.
>>>
>>> for i in items:
>>>  print item[i], "whatever", "\n"
>>>
>>>
>>>  Nope. That would put a newline between each iteration, which is
>> explicitly what the OP did not want.  More importantly, it'd give a syntax
>> error in Python 3, which the OP carefully specified.
>>
>> --
>>
>> DaveA
>>
>>
>
> I'm sorry. Didn't notice the python 3 part, I just joined the list and did
> not look at the OPs post. Sorry about that.
>
> Please bear with me on this, but does the following not print "end" for
> every iteration of "items"?
>
> for item in items:
>  print(item, end="")
>
>
>
>
> --
> Sarma Tangirala,
> Class of 2012,
> Department of Information Science and Technology,
> College of Engineering Guindy - Anna University
>
>


-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Sarma Tangirala
On 6 November 2011 15:47, Dave Angel  wrote:

> On 11/06/2011 04:45 AM, Sarma Tangirala wrote:
>
>> On 6 November 2011 13:11, Peter Otten<__pete...@web.de>  wrote:
>>
>>  Joe Batt wrote:
>>>
>>>  I am learning Python 3 and programming and am very new so please bear

>>> 
>>>
>>>  for item in items:
>>
> ... print(item, end="WHATEVER")
>>>
>>>
>> Another way of writing the above.
>>
>> for i in items:
>>  print item[i], "whatever", "\n"
>>
>>
>>  Nope. That would put a newline between each iteration, which is
> explicitly what the OP did not want.  More importantly, it'd give a syntax
> error in Python 3, which the OP carefully specified.
>
> --
>
> DaveA
>
>

I'm sorry. Didn't notice the python 3 part, I just joined the list and did
not look at the OPs post. Sorry about that.

Please bear with me on this, but does the following not print "end" for
every iteration of "items"?

for item in items:
 print(item, end="")




-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Dave Angel

On 11/06/2011 04:45 AM, Sarma Tangirala wrote:

On 6 November 2011 13:11, Peter Otten<__pete...@web.de>  wrote:


Joe Batt wrote:


I am learning Python 3 and programming and am very new so please bear



for item in items:

... print(item, end="WHATEVER")



Another way of writing the above.

for i in items:
  print item[i], "whatever", "\n"


Nope. That would put a newline between each iteration, which is 
explicitly what the OP did not want.  More importantly, it'd give a 
syntax error in Python 3, which the OP carefully specified.


--

DaveA

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


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Sarma Tangirala
On 6 November 2011 13:11, Peter Otten <__pete...@web.de> wrote:

> Joe Batt wrote:
>
> > I am learning Python 3 and programming and am very new so please bear
> with
> > me…
> > I am writing a program to pull out specific characters in a sequence and
> > then print then out. So far so good however when the characters are
> > printed out they pint on separate lines as opposed to what I want, all on
> > the same line. I have tried \n and just ,  in the pint statement i.e.
> > print(letterGroup[4],) and print(letterGroup[4]\n) and even
> > print(letterGroup[4],/n)…….. Can anyone help and explain please….Thank
> you
>
> The following arrived in a totally messed up formatting:
>
> > for line in file:
> > m = re.search(regexp, line)
> > if m:
> > letterGroup = m.group(0)
> > print(letterGroup[4])
>
> You can specify what to print after the argument(s) with the end keyword
> parameter:
>
> >>> items = 1, 2, 3
> >>> for item in items:
> ... print(item, end=" ")
> ...
> 1 2 3 >>>
> >>> for item in items:
> ... print(item, end="")
> ...
> 123>>>
> >>> for item in items:
> ... print(item, end="WHATEVER")
>


Another way of writing the above.

for i in items:
 print item[i], "whatever", "\n"


...
> 1WHATEVER2WHATEVER3WHATEVER>>>
>
> The default for end is of course newline, spelt "\n" in a Python string
> literal. Use
>
> >>> help(print)
>
> in the interactive interpreter to learn more about the print() function.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing with no newline :(

2011-11-06 Thread Peter Otten
Joe Batt wrote:

> I am learning Python 3 and programming and am very new so please bear with
> me…
> I am writing a program to pull out specific characters in a sequence and
> then print then out. So far so good however when the characters are
> printed out they pint on separate lines as opposed to what I want, all on
> the same line. I have tried \n and just ,  in the pint statement i.e.
> print(letterGroup[4],) and print(letterGroup[4]\n) and even
> print(letterGroup[4],/n)…….. Can anyone help and explain please….Thank you

The following arrived in a totally messed up formatting:

> for line in file:
> m = re.search(regexp, line)
> if m:
> letterGroup = m.group(0)
> print(letterGroup[4])

You can specify what to print after the argument(s) with the end keyword 
parameter:

>>> items = 1, 2, 3
>>> for item in items:
... print(item, end=" ")
...
1 2 3 >>>
>>> for item in items:
... print(item, end="")
...
123>>>
>>> for item in items:
... print(item, end="WHATEVER")
...
1WHATEVER2WHATEVER3WHATEVER>>>

The default for end is of course newline, spelt "\n" in a Python string 
literal. Use

>>> help(print)

in the interactive interpreter to learn more about the print() function.

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


Re: [Tutor] printing a key not a value

2011-10-25 Thread Joel Goldstick
On Tue, Oct 25, 2011 at 9:45 AM, ADRIAN KELLY wrote:

>  if i have a dictionary called definitions is there a way of printing the
> keys and not the values that go with them?
>
> thanks so much
>
>
>
> Adrian
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> The python.org documentation is a good place to learn about dictionaries.
http://docs.python.org/library/stdtypes.html#mapping-types-dict

As it turns out, you can iterate over the keys of a dictionary:

>>> definitions = {'k1':'k1 value', 'k2': 'k2 value'}
>>> for k in definitions:
...   print k
...
k2
k1



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


Re: [Tutor] printing a key not a value

2011-10-25 Thread Dipo Elegbede
>>> definitions =
{'name':'dipo','food':'spaghetti','age':30,'location':'lagos'}
>>> definitions.keys()
['food', 'age', 'name', 'location']
>>> definitions.values()
['spaghetti', 30, 'dipo', 'lagos']
>>>


You can do this to get what you want.
Hope it helps.

On Tue, Oct 25, 2011 at 2:54 PM,  wrote:

> Sure,
>
> mydict = {'a':1, 'b',2}
> for key in mydict:
>print key
>
> Hope this helps,
> Bodsda
> Sent from my BlackBerry® wireless device
>
> -Original Message-
> From: ADRIAN KELLY 
> Sender: tutor-bounces+bodsda=googlemail@python.org
> Date: Tue, 25 Oct 2011 13:45:50
> To: 
> Subject: [Tutor] printing a key not a value
>
> ___
> 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
>



-- 
Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise Application
Development
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing a key not a value

2011-10-25 Thread bodsda
Sure,

mydict = {'a':1, 'b',2}
for key in mydict:
print key

Hope this helps,
Bodsda 
Sent from my BlackBerry® wireless device

-Original Message-
From: ADRIAN KELLY 
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 25 Oct 2011 13:45:50 
To: 
Subject: [Tutor] printing a key not a value

___
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] Printing in the same place

2011-08-17 Thread Alan Gauld

On 17/08/11 23:20, brandon w wrote:


I guess I will have to find another way to create a digital clock in a
tkinter window.


The point about a GUI is that you display widgets that have text on 
them. It could be a Label, or a Button or a Text box or even a Canvas.
Then to change the text you simply replace the text en-masse with a new 
string, you don't attempt to backspace or return or anything like you 
would with print(). (Actually with a Text box widget you could do that 
by controlling the cursor, but for your purpose that is just making it 
harder than it needs to be!)


You just assign a new string to the widgets text attribute.

You can see how to do that with one of the examples on my GUI tutor.
It replaces the text on a label with the contents of an entry box:


# create the event handler to clear the text
def evClear():
  lHistory['text'] = eHello.get()
  eHello.delete(0,END)


the label(lHistory) simply displays whatever is assigned to its text 
attribute, and in this case its whatever is in the Entry widget (eHello) 
before we clear it. It could just as well be a string displaying the 
current time...


HTH,

--
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] Printing in the same place

2011-08-17 Thread brandon w

On 08/17/2011 04:02 AM, Alan Gauld wrote:

On 17/08/11 04:05, brandon w wrote:

I am trying to print in the same place to make a clock in a tkinter
window. I will loop the following code to update the time.

This is not a tkinter program so its completely irrelevant to your
stated aim. In tkinter  how print works is of no importance. You will
not be using print in a tkinter program you will simply be changing
the text in a widget.


This seems to work but it is not printing in the same place:

#!/usr/bin/python
#Python 2.6.6

import time

for t in range(5):
digits = time.strftime('%H:%M:%S')
print "\r", digits
time.sleep(0.1)


That's because you are using \r which is platform dependant
(and even terminal dependant on *nix) . You don't say which
platform you are using. Using \b (backspace) may be more
successful.

>>> print ("test","\b\b\b\b\b\b","Foo")
 Foo

But, as I say, that won't be very useful in tkinter since you
won't be using print().


I am using Linux with Python 2.6.6.

"\b" seems like a good simple solution to the problem.
I guess I will have to find another way to create a digital clock in a 
tkinter window.

I found someone who made a Python clock but I want to create my own version
without just coping his. I will learn more if I try to do it myself.
Thanks for your help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing in the same place

2011-08-17 Thread Alan Gauld

On 17/08/11 09:02, Alan Gauld wrote:

On 17/08/11 04:05, brandon w wrote:
> I am trying to print in the same place to make a clock in a tkinter
> window. I will loop the following code to update the time.
This is not a tkinter program so its completely irrelevant to your
stated aim. In tkinter how print works is of no importance. You will
not be using print in a tkinter program you will simply be changing
the text in a widget.

> This seems to work but it is not printing in the same place:
>
> #!/usr/bin/python
> #Python 2.6.6
>
> import time
>
> for t in range(5):
> digits = time.strftime('%H:%M:%S')
> print "\r", digits
> time.sleep(0.1)

That's because you are using \r which is platform dependant
(and even terminal dependant on *nix) . You don't say which
platform you are using. Using \b (backspace) may be more
successful.

 >>> print ("test","\b\b\b\b\b\b","Foo")
Foo

But, as I say, that won't be very useful in tkinter since you
won't be using print().


Oops, you also need to suppress the newline as Peter Otten mentioned!
You can do that in Python v2 by adding a training comma or in v3 you can
specify no newline as a parameter.

But again, all irrelevent for tkinter.


--
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] Printing in the same place

2011-08-17 Thread Alan Gauld

On 17/08/11 04:05, brandon w wrote:

I am trying to print in the same place to make a clock in a tkinter
window. I will loop the following code to update the time.

This is not a tkinter program so its completely irrelevant to your
stated aim. In tkinter  how print works is of no importance. You will
not be using print in a tkinter program you will simply be changing
the text in a widget.


This seems to work but it is not printing in the same place:

#!/usr/bin/python
#Python 2.6.6

import time

for t in range(5):
digits = time.strftime('%H:%M:%S')
print "\r", digits
time.sleep(0.1)


That's because you are using \r which is platform dependant
(and even terminal dependant on *nix) . You don't say which
platform you are using. Using \b (backspace) may be more
successful.

>>> print ("test","\b\b\b\b\b\b","Foo")
 Foo

But, as I say, that won't be very useful in tkinter since you
won't be using print().

--
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] Printing in the same place

2011-08-17 Thread Peter Otten
brandon w wrote:

> I am trying to print in the same place to make a clock in a tkinter
> window. I will loop the following code to update the time.
> 
> This seems to work but it is not printing in the same place:
> 
> #!/usr/bin/python
> #Python 2.6.6
> 
> import time
> 
> for t in range(5):
>  digits = time.strftime('%H:%M:%S')
>  print "\r", digits
>  time.sleep(0.1)

The print statement automatically adds a newline. Try

sys.stdout.write("\r" + digits)
sys.stdout.flush()

instead of print.

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


Re: [Tutor] Printing RAW string

2011-06-10 Thread Jeremy G Clark
print(repr(s))

_

How i can print the string in raw...as it is

s="hello world\n"
print s

Output:
helloworld

But i want it to be "hello world\n"

I know it can be done by adding a 'r' prefix but is there any other way because 
the string will be taken in during input!

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


Re: [Tutor] Printing output from Python program to HTML

2011-05-10 Thread Spyros Charonis
Thanks, very simple but I missed that because it was supposed be in HTML
code!

On Tue, May 10, 2011 at 1:16 PM, Spyros Charonis wrote:

> Hello everyone,
>
> I have a Python script that extracts some text from a database file and
> annotates another file,
> writing the results to a new file. Because the files I am annotating are
> ASCII,
> I am very restricted as to how I can annotate the text, and I would like to
> instead
> write the results to HTML so that I can annotate my file in more visually
> effective ways,e.g. by changing text color
> where appropriate.  My program extracts text from a database, reads a file
> that is to be annotated, and writes those
> annotations to a newly created (.htm) file
> I include the following headers at the beginning of my program:
>
> print "Content-type:text/html\r\n\r\n"
> print ''
> print ''
>
> The part of the program that finds the entry I want and produces the
> annotation is about
> 80 lines down and goes as follow:
>
> file_rmode = open('/myfolder/alignfiles/query1, 'r')
> file_amode = open('/myfolder/alignfiles/query2, 'a+')
>
> file1 = motif_file.readlines() # file has been created in code not shown
> file2 = file_rmode.readlines()
>
> for line in seqalign:
>for item in finalmotifs:
>item = item.strip().upper()
>if item in line:
>   newline = line.replace(item, "  item
>  ") # compiler complains here about the word "red"
>   # sys.stdout.write(newline)
>   align_file_amode.write(line)
>
> print ''
> print ''
>
> motif_file.close()
> align_file_rmode.close()
> align_file_amode.close()
>
> The Python compiler complains on the line I try to change the font color,
> saying "invalid syntax".  Perhaps I
> need to import the cgi module to make this a full CGI program? (I have
> configured my Apache server). Or alternatively, my HTML code is messed up,
> but I
> am pretty sure this is more or less a simple task.
>
> I am working in Python 2.6.5. Many thanks in advance
>
> Spyros
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing output from Python program to HTML

2011-05-10 Thread Steven D'Aprano

Spyros Charonis wrote:


  newline = line.replace(item, "  item
 ") # compiler complains here about the word "red"


You should pay attention when Python tells you where there is an error. 
If it says there is a syntax error, then your syntax is invalid and you 
need to fix it.



The Python compiler complains on the line I try to change the font color,
saying "invalid syntax".  Perhaps I
need to import the cgi module to make this a full CGI program?


And how will that fix your syntax error?


The offending line of code looks like this:

newline = line.replace(item,
"  item>  ")

split into two lines because my mail program doesn't like long lines. 
The important part is the replacement string:


"  item>  "

Only it's not a string, the syntax is broken. Each quote " starts and 
then stops a string:


OPEN QUOTE ... END QUOTE red OPEN QUOTE ... CLOSE QUOTE

This is invalid syntax. You can't have the word red sitting outside of a 
string like that.


How to fix it? There are two ways. You can escape the inner quotes like 
this:



"  item>  "


That will stop Python using the escaped quotes \" as string delimiters, 
and use them as ordinary characters instead.


Or, you can take advantage of the fact that Python has two different 
string delimiters, double and single quotes, and you can safely nest 
each inside the other:



'  item>  '




--
Steven

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


Re: [Tutor] Printing output from Python program to HTML

2011-05-10 Thread Brett Ritter
On Tue, May 10, 2011 at 8:16 AM, Spyros Charonis  wrote:
>           newline = line.replace(item, "  item
...
> The Python compiler complains on the line I try to change the font color,
> saying "invalid syntax".

Your issue here is not importing libraries, but your quotations.  When
you get to "red", it takes that first double quote as ENDING the
string of HTML that starts with ".  It doesn't know that you're
putting quotes inside your string, as the only way it knows when a
string ends is when it reaches the quoting character that matches the
beginning.

The easiest solution is to use 'red' (using single quotes) as HTML accepts both.

 newline = line.replace(item, "  item  ")

As alternative you could use a different quoting for your string (note
the single quotes on the outside):

newline = line.replace(item, '  item  ')

Alternatively you could escape your string.  This tells Python that
the quotes are NOT ending the string, and the backslashes will not
appear in the resulting output:

 newline = line.replace(item, "  item  ")

Note that the first option works because HTML accepts single or double
quotes for it's attribute values.  The second option works because
single and double quotes for strings work the saem in Python (this is
not true of all languages).  The third option is pretty standard
across languages, but can be annoying because it becomes harder to
cut-and-paste strings to/from other places (for example, template
files, raw HTML files, etc).

Hope that helps!
-- 
Brett Ritter / SwiftOne
swift...@swiftone.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing in python 3.x

2010-12-05 Thread Alan Gauld


"Monte Milanuk"  wrote

... I was under the impression that controlling exactly layout via 
html was kind of difficult and somewhat fragile.


Absolutely true, especially compared to PDF. But its much
better than it was say 10-15 years ago. But if you can construct
the page such that precision layout is not required that isn't
too big a problem.

perhaps less so as one could make some fairly concrete assumptions 
about the paper size being used in this situation.  Is it common to 
use HTML for formatting printed reports?!?  Could you give an 
example of how you'd control the layout of specific fields on a 
printed report?


Its not unknown. It depends on how precise it needs to be.
But if you use tables extensively, with fixed widths etc you can
get fairly good control. Also use CSS stylesheets to control fonts 
etc.

HTML for printing is almost the opposite of HTML for browser display
- you avoid all the flexible size settings etc and use fixed sixes and 
fonts.


The great thing about HTML is that you can very quickly
try things out manually before committing the effort of generating
it by code. If you are in control of the printed output then you 
should

be able to get precision good enough. If not then PDF may be your
best bet. One option is to get the HTML working well then print
to a PDF printer file. Then you can ship the PDF file with its
precise layout but retain the ease of production of the HTML.

--
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] printing in python 3.x

2010-12-04 Thread Monte Milanuk

Alan,

Perhaps this is a silly question (and possibly not strictly 
python-related) but I was under the impression that controlling exactly 
layout via html was kind of difficult and somewhat fragile.  The latter 
perhaps less so as one could make some fairly concrete assumptions about 
the paper size being used in this situation.  Is it common to use HTML 
for formatting printed reports?!?  Could you give an example of how 
you'd control the layout of specific fields on a printed report?


Thanks,

Monte

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


Re: [Tutor] printing in python 3.x

2010-12-03 Thread Alan Gauld


"Rance Hall"  wrote



But shop owner wants to do something nicer with the customer 
receipts.

He is talking shop logos and pdf files.


The simplest technique is probably to generate an HTML file and then
get the OS to print that for you via the default browser.

Google keeps bringing up ReportLib and the python imaging library, 
but

neither have a 3.x compatible version yet.


THats much harder work IMHO than using an HTML file as a template.


Shop owner is talking about eventually being able to save customer
check in tickets and check out tickets on a web site where clients 
can

log in and check on their work.


And HTML woyuld definitely be easier here!


My thought is that this is perfect for PDF files, but they aren't
available on 3.x yet.


Well you could hand crank them, they are just text files after all.
But HTML is much easier to generate by hand!

I looked at word integration and openoffice integration and they 
dont

look ready for 3.x yet either.


The Pywin32 and ctypes modules all work on Python 3 so you
could use COM integration, or even WSH. But HTML stioll gets
my vote.

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] Printing prime numbers

2010-09-30 Thread Steven D'Aprano
On Thu, 30 Sep 2010 11:52:49 pm Emmanuel Ruellan wrote:
> On Thu, Sep 30, 2010 at 1:57 PM,  wrote:
> > 1 is prime
>
> One is /not/ prime. 

There's no need to apologize for pedantry. Saying that one is prime is 
like saying that 2 is an odd number, or that glass is a type of meat.



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


Re: [Tutor] Printing prime numbers

2010-09-30 Thread Emmanuel Ruellan
On Thu, Sep 30, 2010 at 1:57 PM,  wrote:

>
> 1 is prime
>

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


Re: [Tutor] Printing prime numbers

2010-09-30 Thread delegbede
Ok. I will do that as soon As I get back to my workstation.
Sent from my BlackBerry wireless device from MTN

-Original Message-
From: Shashwat Anand 
Date: Thu, 30 Sep 2010 19:11:33 
To: 
Cc: 
Subject: Re: [Tutor] Printing prime numbers

On Thu, Sep 30, 2010 at 5:27 PM,  wrote:

> Hi all,
> I am trying to write a function that prints out which number is prime in
> range (1,500)
> The function would check thru and the print out something like
> 1 is prime
> 2 is prime
> 3 is prime
> 4 is not
> 5 is prime
>
> Please help me.
> Thank you.
>

Can you show us your attempts.
We may try to help where you did wrong.



> Sent from my BlackBerry wireless device from MTN
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
~l0nwlf

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


Re: [Tutor] Printing prime numbers

2010-09-30 Thread Shashwat Anand
On Thu, Sep 30, 2010 at 5:27 PM,  wrote:

> Hi all,
> I am trying to write a function that prints out which number is prime in
> range (1,500)
> The function would check thru and the print out something like
> 1 is prime
> 2 is prime
> 3 is prime
> 4 is not
> 5 is prime
>
> Please help me.
> Thank you.
>

Can you show us your attempts.
We may try to help where you did wrong.



> Sent from my BlackBerry wireless device from MTN
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] Printing time without "if" statement

2010-03-08 Thread spir
On Mon, 8 Mar 2010 18:03:12 +1100
Steven D'Aprano  wrote:

> On Mon, 8 Mar 2010 03:38:49 pm Elisha Rosensweig wrote:
> > Hi,
> >
> > I have an event-based simulator written in Python (of course). It
> > takes a while to run, and I want to have messages printed every so
> > often to the screen, indicating the simulation time that has passed.
> > Currently, every event that occurs follows the following code
> > snippet:
> [...]
> > This seems stupid to me - why should I have to check each round if
> > the time has been passed? I was thinking that there might be a
> > simpler way, using threading, but I have zero experience with
> > threading, so need your help. The idea was to have a simple thread
> > that waited X time (CPU cycles, say) and then read the "current_time"
> > variable and printed it.
> >
> > Any simple (simpler?) solutions to this?
> 
> That's a brilliant idea. I think I will steal it for my own code :)
> 
> (Why didn't I think of it myself? Probably because I almost never use 
> threads...)
> 
> Anyway, here's something that should help:
> 
> 
> import time
> import threading
> 
> class Clock(threading.Thread):
> def __init__(self, *args, **kwargs):
> super(Clock, self).__init__(*args, **kwargs)
> self.finished = False
> def start(self):
> print "Clock %s started at %s" % (self.getName(), time.ctime())
> super(Clock, self).start()
> def run(self):
> while 1:
> if self.finished:
> break
> print "Clock %s still alive at %s" % (
> self.getName(), time.ctime())
> time.sleep(2)
> print "Clock %s quit at %s" % (self.getName(), time.ctime())
> def quit(self):
> print "Clock %s asked to quit at %s" % (
> self.getName(), time.ctime())
> self.finished = True
> 
> def do_work():
> clock = Clock(name="clock-1")
> clock.start()
> # Start processing something hard.
> for i in xrange(8):
> print "Processing %d..." % i
> # Simulate real work with a sleep.
> time.sleep(0.75)
> clock.quit()
> 
> 
> 
> And in action:
> 
> >>> do_work()
> Clock clock-1 started at Mon Mar  8 17:40:42 2010
> Processing 0...
> Clock clock-1 still alive at Mon Mar  8 17:40:43 2010
> Processing 1...
> Processing 2...
> Clock clock-1 still alive at Mon Mar  8 17:40:45 2010
> Processing 3...
> Processing 4...
> Processing 5...
> Clock clock-1 still alive at Mon Mar  8 17:40:47 2010
> Processing 6...
> Processing 7...
> Clock clock-1 still alive at Mon Mar  8 17:40:49 2010
> Clock clock-1 asked to quit at Mon Mar  8 17:40:49 2010
> >>> Clock clock-1 quit at Mon Mar  8 17:40:51 2010
> 
> >>>
> 
> 
> There's a bit of a display artifact in the interactive interpreter, when 
> the final quit message is printed: the interpreter doesn't notice it 
> needs to redraw the prompt. But other than that, it should be fine.

Hello,

really interesting, indeed. I also have no idea about threading in python. But 
as timer is concerned, I would prefere something like:

import time
import whatever_to_ensure_run_in_separate_thread
class Timer(whatever_to_ensure_run_in_separate_thread):
UNIT = 1/100# µs
def __init__(self, delay, action, cyclic=False):
self.delay = delay
self.action = action
self.cyclic = cyclic
self.goon = True
def run(self):
if self.cyclic:
while self.goon:
self.cycle()
else:
self.cycle
def cycle(self):
self.wait()
self.action()
def wait(self):
delay.sleep(self.delay * self.UNIT)

Or even better, launch a signal in main thread -- which is supposed to be an 
event cycle. This is how things work in the field of automation:

class Timer(whatever_to_ensure_run_in_separate_thread):
UNIT = 1/100# µs
def __init__(self, delay, signal, resetDelay=1, cyclic=False):
self.delay = delay
self.signal = signal
self.resetDelay = resetDelay
self.cyclic = cyclic
self.goon = True
def run(self):
if self.cyclic:
while self.goon:
self.cycle()
else:
self.cycle
def cycle(self):
self.wait(self.delay)
self.signal = True
self.wait(self.resetDelay)
self.signal = False
def wait(self, delay):
delay.sleep(delay * self.UNIT)

# main cycle:
t1 = Timer(...)
...
if t1_signal:
do_t1_action

(Actually, in python, the signal may be the index of a Timer.signals boolean 
array, incremented with each new instance.)


Denis
-- 


la vita e estrany

spir

Re: [Tutor] Printing time without "if" statement

2010-03-07 Thread Steven D'Aprano
On Mon, 8 Mar 2010 03:38:49 pm Elisha Rosensweig wrote:
> Hi,
>
> I have an event-based simulator written in Python (of course). It
> takes a while to run, and I want to have messages printed every so
> often to the screen, indicating the simulation time that has passed.
> Currently, every event that occurs follows the following code
> snippet:
[...]
> This seems stupid to me - why should I have to check each round if
> the time has been passed? I was thinking that there might be a
> simpler way, using threading, but I have zero experience with
> threading, so need your help. The idea was to have a simple thread
> that waited X time (CPU cycles, say) and then read the "current_time"
> variable and printed it.
>
> Any simple (simpler?) solutions to this?

That's a brilliant idea. I think I will steal it for my own code :)

(Why didn't I think of it myself? Probably because I almost never use 
threads...)

Anyway, here's something that should help:


import time
import threading

class Clock(threading.Thread):
def __init__(self, *args, **kwargs):
super(Clock, self).__init__(*args, **kwargs)
self.finished = False
def start(self):
print "Clock %s started at %s" % (self.getName(), time.ctime())
super(Clock, self).start()
def run(self):
while 1:
if self.finished:
break
print "Clock %s still alive at %s" % (
self.getName(), time.ctime())
time.sleep(2)
print "Clock %s quit at %s" % (self.getName(), time.ctime())
def quit(self):
print "Clock %s asked to quit at %s" % (
self.getName(), time.ctime())
self.finished = True

def do_work():
clock = Clock(name="clock-1")
clock.start()
# Start processing something hard.
for i in xrange(8):
print "Processing %d..." % i
# Simulate real work with a sleep.
time.sleep(0.75)
clock.quit()



And in action:

>>> do_work()
Clock clock-1 started at Mon Mar  8 17:40:42 2010
Processing 0...
Clock clock-1 still alive at Mon Mar  8 17:40:43 2010
Processing 1...
Processing 2...
Clock clock-1 still alive at Mon Mar  8 17:40:45 2010
Processing 3...
Processing 4...
Processing 5...
Clock clock-1 still alive at Mon Mar  8 17:40:47 2010
Processing 6...
Processing 7...
Clock clock-1 still alive at Mon Mar  8 17:40:49 2010
Clock clock-1 asked to quit at Mon Mar  8 17:40:49 2010
>>> Clock clock-1 quit at Mon Mar  8 17:40:51 2010

>>>


There's a bit of a display artifact in the interactive interpreter, when 
the final quit message is printed: the interpreter doesn't notice it 
needs to redraw the prompt. But other than that, it should be fine.


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


Re: [Tutor] Printing time without "if" statement

2010-03-07 Thread Steve Willoughby
On Sun, Mar 07, 2010 at 11:38:49PM -0500, Elisha Rosensweig wrote:
> Hi,
> 
> I have an event-based simulator written in Python (of course). It takes a
> while to run, and I want to have messages printed every so often to the
> screen, indicating the simulation time that has passed. Currently, every
> event that occurs follows the following code snippet:

It depends on how your system simulates the events and their
scheduling, but you might look at the sched module in the standard
library.  Maybe you would be able to use that to schedule your
simulated events and also schedule periodic time output too.


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


Re: [Tutor] Printing data to a printer...

2010-01-02 Thread Alan Gauld
"Ken G."  wrote

> Wow, I looked and looked.  I can print out my program listing but can 
> not print the resulted data produced by the program.

Printing is always difficult in a modern OS because your program 
and Python cannot be sure of what kind of device it is going to print on.

Unix traditionally did printing by creating a temporary file with 
markup - usually roff markup - and then  sending that file 
through the text processor (eg [gtn]roff) and hence to the 
print spool for processing by lp or lpr.

You can still do that although nowadays I tend to use HTML as 
the formatting language and print via a browser. For simple text 
output you can of course bypass the formatting step and just 
send it straight to lpr, possibly via fmt.
> In Liberty Basic, the command was lprint.  

In the days of standard BASIC the printer was almost certainly 
an Epson compatible ASCII printer which made it pretty easier 
for the interpreter to send output directly. Those days are long 
gone :-(

Its the same with input - there is no direct equivalent to 
inkey$, although curses comes close, because again we now 
have a huge variety of input devices.

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] Printing data to a printer...

2010-01-02 Thread Ken G.



Rich Lovely wrote:

2010/1/2 Ken G. :
  

Wow, I looked and looked.  I can print out my program listing but can not
print the resulted data produced by the program.

How do I print out on my USB printer the data output of my Python program I
ran in my Ubuntu terminal via Geany IDE?
I already wrote several programs using raw_input, files, sort, list, tuple
and I like Python!  Currently, I'm using Python 2.6.  In Liberty Basic, the
command was lprint.  For example:

  print 2 + 2#display in terminal

  lprint 2 + 2#   print result to printer
TIA,

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




There doesn't appear to be anything builtin to make it easy - on
Linux, at least.  There are three options, as far as I can see.  I
don't have a printer, so can't test either.

First is to pipe the output from the program to a command line
printing program.  This will mean that all of the data written to
stdout is sent straight to the printer.  This can only be done at the
command line, and will look something like
$ python your_program.py | lpr

Using this method, you can still send output to the console using
sys.stderr.write()

This is the traditional unix method, but is only really appropriate
for your own scripts.

The second option is to open a pipe to a program such as lpr from
within python, using the subprocess module:

import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(data_to_print)

The third option is to use a third party library.  The current linux
printing system is called CUPS, so you can try searching the
cheeseshop (pypi.python.org) or google for python cups packages.  The
pypi gives one possibility:  http://www.pykota.com/software/pkipplib

There is a fourth option, which might not even work: opening the
printer device as a file-like object (I don't recommend trying this
without doing a lot of research first):

lp = open("/dev/lp0", "w")
lp.write(data_to_print)

Of course, all of this is very much os specific.  The first option
will work in linux, osx and windows, but two and three will only work
in linux and osx, however printing is considerably easier on windows,
there is the win32print package that does (most of) the heavy lifting
for you.  To be honest, I'm not even sure if option four will work
_at_all_.

  
I found a roundabout way of doing it.  Using IDLE, I ran the program as 
it is in the new "untitled window", resulting in having the output in 
the Python Shell window.  I use the Print command from that shell window. 

Thanks for your input.  It is much appreciated and I am printing it out 
for reference.


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


Re: [Tutor] Printing data to a printer...

2010-01-02 Thread Rich Lovely
2010/1/2 Ken G. :
> Wow, I looked and looked.  I can print out my program listing but can not
> print the resulted data produced by the program.
>
> How do I print out on my USB printer the data output of my Python program I
> ran in my Ubuntu terminal via Geany IDE?
> I already wrote several programs using raw_input, files, sort, list, tuple
> and I like Python!  Currently, I'm using Python 2.6.  In Liberty Basic, the
> command was lprint.  For example:
>
>   print 2 + 2    #    display in terminal
>
>   lprint 2 + 2    #   print result to printer
> TIA,
>
> Ken
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

There doesn't appear to be anything builtin to make it easy - on
Linux, at least.  There are three options, as far as I can see.  I
don't have a printer, so can't test either.

First is to pipe the output from the program to a command line
printing program.  This will mean that all of the data written to
stdout is sent straight to the printer.  This can only be done at the
command line, and will look something like
$ python your_program.py | lpr

Using this method, you can still send output to the console using
sys.stderr.write()

This is the traditional unix method, but is only really appropriate
for your own scripts.

The second option is to open a pipe to a program such as lpr from
within python, using the subprocess module:

import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(data_to_print)

The third option is to use a third party library.  The current linux
printing system is called CUPS, so you can try searching the
cheeseshop (pypi.python.org) or google for python cups packages.  The
pypi gives one possibility:  http://www.pykota.com/software/pkipplib

There is a fourth option, which might not even work: opening the
printer device as a file-like object (I don't recommend trying this
without doing a lot of research first):

lp = open("/dev/lp0", "w")
lp.write(data_to_print)

Of course, all of this is very much os specific.  The first option
will work in linux, osx and windows, but two and three will only work
in linux and osx, however printing is considerably easier on windows,
there is the win32print package that does (most of) the heavy lifting
for you.  To be honest, I'm not even sure if option four will work
_at_all_.

-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing xps or gif

2009-12-31 Thread ALAN GAULD



> Well I have a folder with some sub folders that have a combo of xps and gif
> files I want to be able to point the program to it and have it print the
> contents of each sub folder.

In that case I'd use os.walk to traverse 
the folders and find the files.

I'd then use os.system() (or the subprocess 
module for more control) and call whatever 
program you would use to print the files 
from the command line.

ghostscript may do it for the xps files, 
for example.

HTH,

Alan G.
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] printing xps or gif

2009-12-31 Thread Alan Gauld


"Rayon"  wrote 


Can I use python to print xps or gif.


Yes.

But how you do it depends on the context of what you are doing.
Care to expound?

Alan G.

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


Re: [Tutor] Printing Sideway...

2009-11-08 Thread Ken G.
Okay, thanks.  Understood.  It's not a big thing here.  Thought I would 
ask.


Ken

Alan Gauld wrote:



Ken G. wrote:

I am using Ubuntu 9.04 as my primary OS.  I have Windows XP
installed in the first partition (dual boot).  I have Python
2.6.2 installed on both OS.  The printer is a Cannon MX300.
To print on the envelope, I use Windows Works v4.5 which is
easy to use.  I just learned how to print via Open Office
Writer 3.0.1 which took several hours to do properly.

If it is not possible to print sideways, I understand.


It is possible but the solution has nothing to do with Python. That is 
the point Bob is making. How you print sideways depends on the printer 
driver, the application software you are using, and the OS.


ON Unix you can print sideways by doing things like sending print 
formatting codes through any of the print formatting programs in Unix 
- groff being a good example. Or you could create an HTML document 
containing your text and then print that via a browser.
Or you can format the output normally and then programmatically set 
the printer driver options to print in a different orientation.


All of these could be done from Python or via manual intervention.

HTH,


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


Re: [Tutor] Printing Sideway...

2009-11-08 Thread Alan Gauld



Ken G. wrote:

I am using Ubuntu 9.04 as my primary OS.  I have Windows XP
installed in the first partition (dual boot).  I have Python
2.6.2 installed on both OS.  The printer is a Cannon MX300.
To print on the envelope, I use Windows Works v4.5 which is
easy to use.  I just learned how to print via Open Office
Writer 3.0.1 which took several hours to do properly.

If it is not possible to print sideways, I understand.


It is possible but the solution has nothing to do with Python. 
That is the point Bob is making. How you print sideways depends 
on the printer driver, the application software you are using, and 
the OS.


ON Unix you can print sideways by doing things like sending 
print formatting codes through any of the print formatting programs 
in Unix - groff being a good example. Or you could create an 
HTML document containing your text and then print that via a browser.
Or you can format the output normally and then programmatically 
set the printer driver options to print in a different orientation.


All of these could be done from Python or via manual intervention.

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] Printing Sideway...

2009-11-07 Thread bob gailer
Please always reply-all so a copy goes to the list. I am ccing this to 
the lists for you.


Ken G. wrote:

I am using Ubuntu 9.04 as my primary OS.  I have Windows XP
installed in the first partition (dual boot).  I have Python
2.6.2 installed on both OS.  The printer is a Cannon MX300.
To print on the envelope, I use Windows Works v4.5 which is
easy to use.  I just learned how to print via Open Office
Writer 3.0.1 which took several hours to do properly.

If it is not possible to print sideways, I understand.


That depends on the software (Windows Works / Open Office) and the printer.

How do you communicate from Python to these programs?





Instead of printing from left to right on the long side of
a #10 envelope, I wish to print sideway, printing from the
left short edge of envelope to its right short edge.








--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing Sideway...

2009-11-07 Thread bob gailer

Ken G. wrote:

It is possible to print letters sideway in Python?


Python is a programming language, not a printer driver.

So this is not the best place to ask the question.

But tell us more -

 what OS? (Windows or what)
 what printer? (Make and model)
 what are you doing in Python to print the envelope now?


Instead of printing from left to right on the long side of
a #10 envelope, I wish to print sideway, printing from the
left short edge of envelope to its right short edge.



--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing tree structure

2009-07-03 Thread Dave Angel

karma wrote:

Hi all ,

I have a nested list in the structure
[root,[leftSubtree],[RightSubtree]] that I want to print out. I was
thinking that a recursive solution would work here, but so far I can't
quite get it working. This is what I have so far:

Can someone suggest whether this is suited to a recursive solution and
if so, what am I doing wrong.

Thanks

  

L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]]
def printTree(L):


for i in L:
   if isinstance(i,str):
   print 'Root: ', i
   else:
  print '--Subtree: ', i
  printTree(i)


  

printTree(L)


Root:  a
--Subtree:  ['b', ['d', [], []], ['e', [], []]]
Root:  b
--Subtree:  ['d', [], []]
Root:  d
--Subtree:  []
--Subtree:  []
--Subtree:  ['e', [], []] # this shouldn't be here
Root:  e
--Subtree:  []
--Subtree:  []
--Subtree:  ['c', ['f', [], []], []]
Root:  c
--Subtree:  ['f', [], []]
Root:  f
--Subtree:  []
--Subtree:  []
--Subtree:  []

  
Using tabs in Python source code is never a good idea, and mixing tabs 
and spaces is likely to cause real problems, sometimes hard to debug.  
That's not the problem here, but I wanted to mention it anyway.


The problem you have is the hierarchy doesn't show in the printout.  
There are a few ways to indicate it, but the simplest is indentation, 
the same as for Python source code.  Once things are indented, you'll 
see that the line you commented as "this shouldn't be here" is correct 
after all.


Add an additional parameter to the function to indicate level of 
indenting.  Simplest way is to simply pass a string that's either 0 
spaces, 4 spaces, etc.



L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]]
def printTree(L, indent=""):
   for i in L:
   if isinstance(i,str):
   print indent, 'Root: ', i
   else:
   print indent, '--Subtree: ', i
   printTree(i, indent+"")

printTree(L)

Root:  a
--Subtree:  ['b', ['d', [], []], ['e', [], []]]
Root:  b
--Subtree:  ['d', [], []]
Root:  d
--Subtree:  []
--Subtree:  []
--Subtree:  ['e', [], []]
Root:  e
--Subtree:  []
--Subtree:  []
--Subtree:  ['c', ['f', [], []], []]
Root:  c
--Subtree:  ['f', [], []]
Root:  f
--Subtree:  []
--Subtree:  []
--Subtree:  []

Now I don't know if that's what your list of lists was supposed to mean, 
but at least it shows the structure of your printTree() loop.


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


Re: [Tutor] printing tree structure

2009-07-03 Thread karma
Thanks all for the feedback. As you all rightly pointed out, I was
confusing myself by not keeping a track of the recursion depth.

Thanks again

2009/7/3 Alan Gauld :
>
> "karma"  wrote
>
>> thinking that a recursive solution would work here, but so far I can't
>> quite get it working. This is what I have so far:
>>
>> Can someone suggest whether this is suited to a recursive solution and
>
> Yes certainly
>
>> if so, what am I doing wrong.
>
> L = ['a',
>
>                    ['b',                          ['d', [], [] ],
>                ['e', [], [] ]
>                     ],                    ['c',
>  ['f', [], [] ],                          []
>                     ]
>                  ]
>
> def printTree(L):
>>
>> for i in L:
>>          if isinstance(i,str):
>>               print 'Root: ', i
>>          else:
>>                print '--Subtree: ', i
>>                printTree(i)
>>
>
> printTree(L)
>>
>> Root:  a
>> --Subtree:  ['b', ['d', [], []], ['e', [], []]]
>> Root:  b
>> --Subtree:  ['d', [], []]
>> Root:  d
>> --Subtree:  []
>> --Subtree:  []
>
> This is the end of the recursive call to printTree( ['d', [ [], [] ] ]
>
>> --Subtree:  ['e', [], []] # this shouldn't be here
>
> This is the next element in printTree( ['d', [], []], ['e', [], []] )
>
>> Root:  e
>
> This is the start of printTree( ['e', [], [] ]  )
>
>> --Subtree:  []
>> --Subtree:  []
>
> Now why do you think the line you highlighted is an error?
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing tree structure

2009-07-03 Thread Alan Gauld


"karma"  wrote


thinking that a recursive solution would work here, but so far I can't
quite get it working. This is what I have so far:

Can someone suggest whether this is suited to a recursive solution and


Yes certainly


if so, what am I doing wrong.


L = ['a', 
['b', 
  ['d', [], [] ], 
  ['e', [], [] ]
 ], 
['c', 
  ['f', [], [] ], 
  []

 ]
  ]


def printTree(L):

for i in L:
  if isinstance(i,str):
   print 'Root: ', i
  else:
print '--Subtree: ', i
printTree(i)




printTree(L)

Root:  a
--Subtree:  ['b', ['d', [], []], ['e', [], []]]
Root:  b
--Subtree:  ['d', [], []]
Root:  d
--Subtree:  []
--Subtree:  []


This is the end of the recursive call to printTree( ['d', [ [], [] ] ]


--Subtree:  ['e', [], []] # this shouldn't be here


This is the next element in printTree( ['d', [], []], ['e', [], []] )


Root:  e


This is the start of printTree( ['e', [], [] ]  )


--Subtree:  []
--Subtree:  []


Now why do you think the line you highlighted is an error?


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

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


Re: [Tutor] printing tree structure

2009-07-03 Thread Lie Ryan
karma wrote:
> Hi all ,
> 
> I have a nested list in the structure
> [root,[leftSubtree],[RightSubtree]] that I want to print out. I was
> thinking that a recursive solution would work here, but so far I can't
> quite get it working. This is what I have so far:
> 
> Can someone suggest whether this is suited to a recursive solution and
> if so, what am I doing wrong.
> 
> Thanks
> 
 L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]]
 def printTree(L):
>   for i in L:
>if isinstance(i,str):
>  print 'Root: ', i
>  else:
>   print '--Subtree: ', i
>   printTree(i)
> 
> 
 printTree(L)
> Root:  a
> --Subtree:  ['b', ['d', [], []], ['e', [], []]]
> Root:  b
> --Subtree:  ['d', [], []]
> Root:  d
> --Subtree:  []
> --Subtree:  []
> --Subtree:  ['e', [], []] # this shouldn't be here

Why shouldn't it be there? Look more closely:

Root:  b
--Subtree:  ['d', [], []]
  ...
--Subtree:  ['e', [], []]
  ...

The program recurse correctly, however the way you're printing it is
misleading. When printing trees with arbitrary depth, you usually want
to keep track of the recursion depth. Something like this:

def print_tree(tree, depth=0):
...
print_tree(node, depth + 1)
...

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


Re: [Tutor] printing a list to a window

2009-06-16 Thread Alan Gauld

"Essah Mitges"  wrote

What I am trying to do is print a high score text file 
to a pygame window it kinda works...


How do you define kinda?
It doesn't look like it works to me.

The function main defined as

def main():
   high_file = open_file("high_score.txt", "r")
   score = next_block(high_file)
   global score
   high_file.close()

score is a local variable and has a value assigned
Then you use gloobal which will have no affect so far 
as I can tell.


Finally this function is being replaced by the 
second function main you defined.


You might like to try getting it to work by printing on a 
console first! Then worry about the GUI bits.


HTH,

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

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


Re: [Tutor] printing a list to a window

2009-06-16 Thread Wayne
On Tue, Jun 16, 2009 at 4:27 PM, Essah Mitges  wrote:

>
> What I am trying to do is print a high score text file to a pygame window
> it kinda works...I don't know how to go about doing this...
>

Do you know how to print text to a window?

to read a file, just in a terminal window:

f = open('somefile.txt', 'r')

for line in f.readlines():
  print line

Just translate that.

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


Re: [Tutor] Printing Problem python 3

2009-04-29 Thread Vern Ceder

Dave Crouse wrote:

I got the same thing with idle, but when running as a script, it's not
the same, it errors. I tried it on Windows and Linux.

---

[da...@arch64 Python]$ less test.py
#/usr/bin/python3
print ('The \"This is a test \" {')

[da...@arch64 Python]$ sh test.py
test.py: line 3: syntax error near unexpected token `'The \"This is a
test \" {''
test.py: line 3: `print ('The \"This is a test \" {')'


Maybe I'm missing something, but this error is because you're running a 
Python script using the Linux shell, probably bash as the interpreter 
instead of Python. Also, if you're running it on its own as a script, 
you'd want to add a '!' after the '#' - otherwise it's just a comment, 
not setting the interpreter.


To run a Python file as a script, you'd need to do:

[da...@arch64 Python]$ python3 test.py
(or just ./test.py if it's executable and the interpreter is set using 
'#!/usr/bin/python3')


When I do that, it works for me just fine without doubling the '{'

Cheers,
Vern
--
This time for sure!
   -Bullwinkle J. Moose
-
Vern Ceder, Director of Technology
Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804
vce...@canterburyschool.org; 260-436-0746; FAX: 260-436-5137
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing Problem python 3

2009-04-29 Thread Dave Crouse
I got the same thing with idle, but when running as a script, it's not
the same, it errors. I tried it on Windows and Linux.

---

[da...@arch64 Python]$ less test.py
#/usr/bin/python3
print ('The \"This is a test \" {')

[da...@arch64 Python]$ sh test.py
test.py: line 3: syntax error near unexpected token `'The \"This is a
test \" {''
test.py: line 3: `print ('The \"This is a test \" {')'


[da...@arch64 Python]$ python3
Python 3.0.1 (r301:69556, Feb 22 2009, 14:12:04)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print ('The \"This is a test \" {')
The "This is a test " {
>>>
---

However the double quotes was exactly what the doctor ordered ! :)



2009/4/29 "Shantanoo Mahajan (शंतनू महाजन)" :
> print ('The \"This is a test \" {')
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing Problem python 3

2009-04-29 Thread Shantanoo Mahajan (शंत नू महा जन)

On 30-Apr-09, at 12:12 AM, Dave Crouse wrote:


Trying to print something with a { in it.
Probably extremely simple, but it's frustrating me.  :(

print ('The \"This is a test \" {')

i get this error

ValueError: Single '{' encountered in format string



Worked perfectly for me.
===
$ python3.0
Python 3.0 (r30:67503, Jan 14 2009, 09:13:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print ('The \"This is a test \" {')
The "This is a test " {
>>>
===

- shantanoo

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


Re: [Tutor] Printing Problem python 3

2009-04-29 Thread Dave Crouse
The double {{ }} worked perfectly, THANK YOU !  :)

This was driving me crazy.

On Wed, Apr 29, 2009 at 2:03 PM, Kent Johnson  wrote:

> print ('The \"This is a test \" {')
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing Problem python 3

2009-04-29 Thread Kent Johnson
On Wed, Apr 29, 2009 at 2:42 PM, Dave Crouse  wrote:
> Trying to print something with a { in it.
> Probably extremely simple, but it's frustrating me.  :(
>
> print ('The \"This is a test \" {')
>
> i get this error
>
> ValueError: Single '{' encountered in format string

It works for me:
Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print ('The \"This is a test \" {')
The "This is a test " {

I guess you have redefined print() to use the latest style of string formatting:
http://www.python.org/dev/peps/pep-3101/

Try using double braces {{

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


Re: [Tutor] printing files

2009-03-26 Thread Alan Gauld

"Kent Johnson"  wrote
On Thu, Mar 26, 2009 at 2:58 PM, ALAN GAULD  
wrote:

Use '\n'.join(handle[1:])
It will create a string from your list with newline as separator.


The lines from readlines() include the newlines already.


Ah, OK, I couldn't remember if readlines stripped them off or not.


print>>out, handle[1:]

 In the out file, it saves the lines as a list rather than as a string.



use
 out.writelines(handle[1:])


Or if you really want to use the print style

print>>out, ''.join(handle[1:])

ie join the lines using an empty string.

Alan G



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


Re: [Tutor] printing files

2009-03-26 Thread Kent Johnson
On Thu, Mar 26, 2009 at 2:58 PM, ALAN GAULD  wrote:
> Use '\n'.join(handle[1:])
> It will create a string from your list with newline as separator.

The lines from readlines() include the newlines already.

> When i use the following
>
> print>>out, handle[1:]
>
> In the out file, it saves the lines as a list rather than as a string. How
> to avoid this.

use
  out.writelines(handle[1:])

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


Re: [Tutor] printing files

2009-03-26 Thread ALAN GAULD
Use '\n'.join(handle[1:])

It will create a string from your list with newline as separator.

 Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/






From: Bala subramanian 
To: Alan Gauld 
Sent: Thursday, 26 March, 2009 6:11:59 PM
Subject: Re: [Tutor] printing files

yes you are right,
When i use the following

print>>out, handle[1:]

In the out file, it saves the lines as a list rather than as a string. How to 
avoid this. 

Bala


On Thu, Mar 26, 2009 at 7:05 PM, Alan Gauld  wrote:


"Bala subramanian"  wrote


for files in flist:
 handle=open(flist).readlines()
 print>>out, handle  


 print>>out, handle[1:]

Should do it? You might need to handle line endings though...  
Alan G.


___
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] printing files

2009-03-26 Thread Alan Gauld


"Bala subramanian"  wrote


for files in flist:
  handle=open(flist).readlines()
  print>>out, handle  


  print>>out, handle[1:]

Should do it? You might need to handle line endings though...  


Alan G.

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


Re: [Tutor] printing files

2009-03-26 Thread Marc Tompkins
On Thu, Mar 26, 2009 at 10:56 AM, Marc Tompkins wrote:

> Without changing anything else, you could do it with a slice:
>

You should probably also close your input files when you're done with them.

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


Re: [Tutor] printing files

2009-03-26 Thread Marc Tompkins
On Thu, Mar 26, 2009 at 10:42 AM, Bala subramanian <
bala.biophys...@gmail.com> wrote:

>print>>out, handle  <-- Here i want to write only from second line. I
> dnt want to loop over handle here and putting all lines except the first one
> in
> another variable. Is there any
> fancy way of doing it.
>


Without changing anything else, you could do it with a slice:

flist=glob.glob(*.txt)
> out=open('all','w')
>
> for files in flist:
>handle=open(flist).readlines()
>print>>out, handle[1:]  # start with second item (indexes start at 0,
> remember) and go to end
> out.close()
>


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


Re: [Tutor] Printing the code of a function

2008-12-29 Thread Kent Johnson
On Sun, Dec 28, 2008 at 8:49 PM, wormwood_3  wrote:
> Hello all,
>
> This might be trivially easy, but I was having a hard time searching on it
> since all the component terms are overloaded:-) I am wondering if there is a
> way to print out the code of a defined function.

If the source code is available try inspect.getsource().

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


Re: [Tutor] Printing the code of a function

2008-12-29 Thread spir
On Mon, 29 Dec 2008 09:18:43 -
"Alan Gauld"  wrote:

> 
> "wormwood_3"  wrote
> 
> > I am wondering if there is a way to print out the code of a defined 
> > function.
> 
> Its not reliable but I think you can use
> 
> func.func_code.filename
> func.func_code.firstlineno
> 
> To find the first line of code in the original source file.
> Its up to you to figure out the last line though! I guess checking
> for the next line with equivalent indentation might work.
> 
> But I'm not sure how much good it would do you... unless you
> were writing a debugger maybe?
> 
> Alan G

I would do it so by parsing source file:

* (convert indents to tabs (easier to parse))
* search for a line that start with (n indents) + "def func_name"
* record all following lines that start with (n+1 indents) or more
* stop where a line starts with (n indents) or less

denis

--
la vida e estranya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing the code of a function

2008-12-29 Thread Alan Gauld


"wormwood_3"  wrote

I am wondering if there is a way to print out the code of a defined 
function.


Its not reliable but I think you can use

func.func_code.filename
func.func_code.firstlineno

To find the first line of code in the original source file.
Its up to you to figure out the last line though! I guess checking
for the next line with equivalent indentation might work.

But I'm not sure how much good it would do you... unless you
were writing a debugger maybe?

Alan G


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


Re: [Tutor] Printing the code of a function

2008-12-28 Thread wormwood_3
I actually didn't have a definite use case in mind, it was pure curiosity that 
arose while writing a few simple test functions. After having considered it 
more, I can't come up with a case where it would really be necessary, so I 
apologize for that. It makes sense why it wouldn't be possible without a 
disassembler now. Thanks for the info!

 ___
Samuel Huckins


Homepage - http://samuelhuckins.com
Tech blog - http://dancingpenguinsoflight.com/
Photos - http://www.flickr.com/photos/samuelhuckins/
AIM - samushack | Gtalk - samushack | Skype - shuckins





From: bob gailer 
To: wormwood_3 
Cc: tutor@python.org
Sent: Sunday, December 28, 2008 9:07:12 PM
Subject: Re: [Tutor] Printing the code of a function

wormwood_3 wrote: 
Hello
all,

This might be trivially easy, but I was having a hard time searching on
it since all the component terms are overloaded:-) I am wondering if
there is a way to print out the code of a defined function. 
Python does not store the source when compiling things. So the short
answer is NO.

There are some "disassemblers" for Python but I have no experience with
them. They will not be able to reconstruct the exact source.

But ... why do you want to do this? Perhaps if we had more information
about the "use case" we could steer you to a solution.


So
if I have:

def foo():
print "Show me the money."

then I would like to do something like:

>>> foo.show_code
def foo():
print "Show me the money."

I checked out everything in dir(foo), but everything that looked
promising (namely foo.func_code), didn't end up being anything close.

Thanks for any help!

Cordially,
Sam

 
___
Samuel Huckins


Homepage - http://samuelhuckins.com
Tech blog - http://dancingpenguinsoflight.com/
Photos - http://www.flickr.com/photos/samuelhuckins/
AIM - samushack | Gtalk - samushack | Skype - shuckins 




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


-- 
Bob Gailer
Chapel Hill NC 
919-636-4239___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >