change the first character of the line to uppercase in a text file

E

Emile van Sebille

On 6/27/2009 3:39 AM Angus Rodgers said...
On Fri, 26 Jun 2009 18:58:27 -0700 (PDT), powah

Thank you for your hint.
This is my solution:
f = open('test', 'r')
for line in f:
print line[0].upper()+line[1:],

Will your program handle empty lines of input correctly?


It will when the final line is changed to:

print line[:1].upper()+line[1:]
'line' will _never_ be ''. If a line ends with a newline then that will
be preserved returned as part of the string. This applies to the 'file'
methods 'readline', 'readlines', etc, and the iterator, which returns a
line. 'readline' will return '' only when it has reached the end of the
file.
[/QUOTE]
Sorry -- habit. I tend to use that technique to avoid IndexErrors as a
matter of course.

Emile
 
S

Steven D'Aprano

But then that line wouldn't be empty either.

If there is an empty line not terminated by a newline after the last
newline, then that is called 'end-of-file' :=)


I try to always write file-handling files under the assumption that some
day somebody (possibly me) will pass the function a file-like object, and
therefore make the minimum number of assumptions about each line.

For example, I wouldn't assume that lines can't be empty, or that they
must end in a newline. The later is violated even by ordinary files, but
the former could be violated by a file-like object which iterated over
(say) ['first line', 'second line', '', 'the previous line was blank'].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,905
Latest member
Kristy_Poole

Latest Threads

Top