Main Content

The fencepost problem

Archive - Originally posted on "The Horse's Mouth" - 2006-01-10 03:03:12 - Graham Ellis

If you erect a fence of 10 panels, you'll need 11 fenceposts to hold it up. And if you write a program that joins together 10 elements on a line, you'll only need 9 separators between them - this is known as the "fencepost problem".

If you write a simple program loop to output each element from a list followed by a separator, you'll end with a spurious separator on the end of the line. Here's what I mean (in Python).

posts = ["apple","banana","cherry"]
panel = "and"
for place in posts:
print place,panel,
print

which gives the result

apple and banana and cherry and

It would be possible - but long winded - to print out the connecting panel only for the second and subsequent posts:
posts = ["apple","banana","cherry"]
panel = "and"
i = 0
for place in posts:
if i: print panel,
i += 1
print place,
print

but surely there's a better way?? Yes - there is.


In Python, the join method lets me connect a list of strings using another string as the glue between them. My example becomes:
posts = ["kiwi","orange","pineapple"]
panel = " with "
salad = panel.join(posts)
print salad

which gives the result

kiwi with orange with pineapple


Link - full source code


In Perl, the join function performs the same task:
@salad = ("Cherry","Damson",Fig");
print (join(" and ",@salad));



With PHP, the function you'll use is implode:
$salad = array("tangerine","pear","grape");
$fsal = implode(" and ",$salad);