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

Emile van Sebille emile at fenx.com
Sat Jun 27 23:01:40 CEST 2009


On 6/27/2009 1:25 PM MRAB said...
> Emile van Sebille wrote:
>> On 6/27/2009 3:39 AM Angus Rodgers said...
>>> On Fri, 26 Jun 2009 18:58:27 -0700 (PDT), powah
>>> <wong_powah at yahoo.ca> wrote:
>>>
>>>> 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.
> 
Sorry -- habit.  I tend to use that technique to avoid IndexErrors as a 
matter of course.

Emile




More information about the Python-list mailing list