New submission from Steven D'Aprano:

It is moderately common to want to join a sequence of substrings with a 
delimiter rather than a separator, e.g. when joining a sequence of lines into a 
single string, you usually want a trailing newline as well as newlines between 
the lines. E.g.:

'\n'.join(['first', 'second', 'third'])

returns 'first\nsecond\nthird' but we usually want a trailing newline as well, 
but only if the iterable being joined is not empty. If there are no substrings, 
we don't want to append the delimiter.

Currently the most obvious way to do this is to use a temporary variable:

lines = '\n'.join(substrings)
if lines:
    lines += '\n'

I propose adding a keyword-only argument to str.join(), "suffix", to specify an 
optional trailing substring added only if the iterable is non-empty. To join 
lines as above, you would write:

process('\n'.join(substrings, suffix='\n'))

eliminating the unnecessary temporary variable.

Here's a proof of concept:

def join(iterable, sep, *, suffix=None):
    s = sep.join(iterable)
    if s and suffix is not None:
        s += suffix
    return s

messages: 276971
nosy: steven.daprano
priority: normal
severity: normal
status: open
title: Add optional suffix to str.join
type: enhancement
versions: Python 3.7

Python tracker <>
Python-bugs-list mailing list

Reply via email to