[Tutor] Adding line numbers to a Python Script
Alan Gauld
alan.gauld at btinternet.com
Sat Jun 12 22:10:20 CEST 2010
"Sudip Bhattacharya" <sudipb at sudipb.com> wrote
> for line in fileinput.input(inplace = true)............(2)
> line = line.rstrip()........................................(3)
> num=fileinput.lineno()..................................(4)
> print '%-40s #%2i' %(line,num).....................(5)
>
> Line (3) - Are we stripping the entire line of code first, inserting
> the
> code at the end (line (5)) and then placing it back at the same
> place ?
Fire up the python interpreter and type:
>>> help("".strip)
See if you understand what it says. If not come back here and ask
again.
Python's help fuinction is very powerful, learn to use it for fast
answers.
> Line (5) - What does the individual characters in the expression
> "Print
> '%-40s #%2i' %(line,num)" mean ?
These are formatting characters. If you read the Simple Sequences
topic in my tutor you will get some easier examples to try.
Then read the Python documentation - search for format string...
> - '-40s' : is this the space [what does "-40s" mean] that we are
> creating post - which the line nos is inserted "#%2i" ?
Again fitre up the Python interpreter and try it out.
>>> "%-40s" % "Some string here"
Now try again with a different number, Try missing out the minus sign.
Can you see what the different bits do?
Now go read the documentation again. Try some different data types.
Experiment. Its the best way to really understand.
> - What does '%2" mean ? - Is that 2 cursor spaces of width ?
Close but again Read the docs, try it, experiment. See for yourself.
>>> "%2i" % 7
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list