Avoid newline at the end

Paul Hankin paul.hankin at gmail.com
Sun Nov 11 05:36:03 EST 2007


On Nov 11, 10:22 am, Florian Lindner <Florian.Lind... at xgm.de> wrote:
> Hello,
> I have a piece of code like that:
>
>     for row in resultSet:
>         logs += "/home/%s/%s/log/access.log \n" % (row[1], row[0])
>         logs += "/home/%s/%s/log/error.log \n" % (row[1], row[0]) # <--
>
> Now I want to avoid the newline at the last iteration and only at the second
> line.
> How to do that most elegantly with Python?

Naively after your code...
logs = logs.rstrip()

But probably, I'd have constructed the list of logs, then used 'join'
to build the string.

logs = []
for row in resultSet:
    for name in ('access.log', 'error.log'):
        logs += ['/home/%s/%s/log/%s' % (row[1], row[0], name)]
logs = '\n'.join(logs)

Or equivalently using a list comprehension...

logs = '\n'.join('/home/%s/%s/log/%s' % (row[1], row[0], name)
    for row in resultSet
    for name in ('access.log', 'error.log'))

--
Paul Hankin




More information about the Python-list mailing list