Welcome, guest | Sign In | My Account | Store | Cart

Sometimes it's useful to print singular or plural versions of a word, depending on the value of the number of items that the word is describing: for example, "0 files", "1 file", "2 files" (note that "file" is used in the case of 1; "files" otherwise). This idiom does this inline, as a single expression.

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> n = 0
>>> print "%d item%s" % (n, "s"[n==1:])
0 items
>>> n = 1
>>> print "%d item%s" % (n, "s"[n==1:])
1 item
>>> n = 2
>>> print "%d item%s" % (n, "s"[n==1:])
2 items

# If you might want to print negative items, add abs to the test:
>>> n = -1
>>> print "%d item%s" % (n, "s"[abs(n)==1:])
2 items

# If a word has irregular plural morphology, use a list:
>>> n=1
>>> print "%d %s" % (n, ['abacus','abaci'][n!=1])
1 abacus
>>> n=2
>>> print "%d %s" % (n, ['abacus','abaci'][n!=1])
2 abaci

The idiom is "%d item%s" % (n, "s"[n==1:]). "s"[n==1:] evaluates to the empty string when n==1, and to "s" otherwise.

The code in the example could be wrapped into a utility function (e.g. 'printItems') or turned into a function to pluralize a word, but usually you want to do this once or twice in a program that doesn't otherwise do any text processing, so it's nice to avoid the conceptual overhead of adding a function, especially in problem domain that's unrelated to the rest of your program. Of course, it's not very readable unless you've seen it before. That's why it's an idiom.

(Common Lisp provides this functionality with the ~P directive: (format nil "~D item~:P" n) => "3 items"]

1 comment

Robin Parmar 20 years, 1 month ago  # | flag

function version. Cute! Here is a useful function version.

def Plural(num=0, text=''):
    return "%d %s%s" % (num, text, "s"[num==1:])
Created by Oliver Steele on Thu, 11 Oct 2001 (PSF)
Python recipes (4591)
Oliver Steele's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks