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

Peter Otten __peter__ at web.de
Sat Jun 27 13:49:57 CEST 2009


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.





More information about the Python-list mailing list