[Newbie]Trouble with string method

Robert Brewer fumanchu at amor.org
Fri Mar 26 13:31:00 EST 2004


calpolynate wrote:
> "Robert Brewer" <fumanchu at amor.org> wrote in message 
> news:<mailman.431.1080255513.742.python-list at python.org>...
> > I think he wanted the output to be lowercase, not just sorted
> > case-insensitively (that's how I read it anyway). Try:
> > 
> > lines = [line.lower() for line in open('unsorted', 'r')]
> > lines.sort()
> > sorted = open('sorted', 'w')
> > sorted.writelines(lines)
> > sorted.close()
> 
> Yes Robert,
> 
> That's what I was looking for. Sean's worked too, but it sorted
> without changing uppercase to lowercase, I should have been more
> detailed in what I was trying to do.
> 
> How should I go about creating an exception for changing from upper to
> lower? I.E., if the latter part of a line has a comment (#XYZ) and I
> would like to keep those uppercase, what would be a good way to
> implement that in with the existing code?

That depends on whether you want the entire line to keep its case, or
just the comment. Either way, you need to unpack the list comprehension
(the first line, above) into a normal for loop:

lines = []
for line in open('unsorted', 'r'):
    if not has_comment(line):
        line = line.lower()
    lines.append(line)
lines.sort()
sorted = open('sorted', 'w')
sorted.writelines(lines)
sorted.close()

...the above leaves lines with a comment untouched, and lowercases all
other lines. I leave the definition of has_comment() to you--if you
can't figure that one out, then I'm starting to smell homework, Mr.
Calpoly. ;)


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
 




More information about the Python-list mailing list