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

Angus Rodgers twirlip at bigfoot.com
Sat Jun 27 08:01:27 EDT 2009


On Sat, 27 Jun 2009 13:49:57 +0200, Peter Otten 
<__peter__ at web.de> wrote:

>Angus Rodgers wrote:
>
>> On Sat, 27 Jun 2009 13:02:47 +0200, Peter Otten
>> <__peter__ at web.de> wrote:
>> 
>>>Angus Rodgers wrote:
>>>
>>>> On Sat, 27 Jun 2009 11:39:28 +0100, I asked rhetorically:
>>>>
>>>>>Will your program handle empty lines of input correctly?
>>>> 
>>>> Strangely enough, it seems to do so, but why?
>>>
>>>Because there aren't any. When you read lines from a file there will
>>>always be at least the newline character. Otherwise it would indeed fail:
>>>
>>>>>> for line in "peter\npaul\n\nmary".splitlines():
>>>...     print line[0].upper() + line[1:]
>>>...
>>>Peter
>>>Paul
>>>Traceback (most recent call last):
>>>  File "<stdin>", line 2, in <module>
>>>IndexError: string index out of range
>> 
>> Hmm ... the \r\n sequence at the end of a Win/DOS 
>
>line
>
>> seems to be treated as a single character.
>
>Yes, but "\n"[1:] will return an empty string rather than fail.

Yes, I understood that, and it's logical, but what was worrying me
was how to understand the cross-platform behaviour of Python with
regard to the different representation of text files in Windows
and Unix-like OSs. (I remember getting all in a tizzy about this
the last time I tried to do any programming.  That was in C++,
about eight years ago.  Since then, I've only written a couple of
short BASIC programs for numerical analysis on a TI-84+ calculator,
and I feel as if I don't understand ANYTHING any more, but I expect
it'll come back to me.  Sorry about my recent flurry of confused
posts!  If I have any silly questions of my own, I'll post then to
the Tutor list, but in this instance, I imagined I knew what I was
talking about, and didn't expect to get into difficulties ...)  8-P

-- 
Angus Rodgers



More information about the Python-list mailing list