2

All too often I see websites do things like 1 views, 1 days left, or 1 answers. To me this is just lazy as its often as easy to fix as something like:

if(views == 1)
   print views + " view"
else print views + " views"

What I want to know is if there is a one liner in a common language like java, python, php, etc., something that I can comment on sites that do this and say, its as easy as adding this to your code. Is that possible?

eliot
  • 1,319
  • 1
  • 14
  • 33

3 Answers3

3

I use ternary operators when handling this on my sites. It looks like many c-based programming languages support ternary operators. It is as easy as this in php:

<?= $views . ' view' . ($views == 1 ? '' : 's'); ?>
Eric B
  • 321
  • 2
  • 7
  • 2
    For Java: `System.out.println(numAnswers + " answer" + (numAnswers == 1 ? "" : "s"));` Where `numAnswers` is an `int` holding how many answers there are, of course. – asteri Mar 26 '13 at 19:52
  • @asteri I'd repost that as a standalone answer. It's very useful. – Stevoisiak Apr 03 '17 at 18:07
  • I prefer to write complete words, so instead of `'%d view%s' % (views, views == 1 ? '' : 's')`, I rather write `'%d %s' % (views, views == 1 ? 'view' : 'views')`. Translating parts of words is as bad as translating parts of sentences. Let your code express the idea as clearly as possible. For example, my style words for the word 'children' as well. Oh, and by the way, the above only works for English. Adding proper i18n support will solve this particular problem as a side effect. – Roland Illig Jan 29 '22 at 10:55
1

If you are using django (python) you can use the pluralize filter:

You have {{ num_messages }} message{{ num_messages|pluralize }}.

It has support for special cases too. Have a look at the documentation.

If you want to do something similar in normal python code, have a look at the inflect module. It looks like it can be pretty powerful, and apparently guesses most plurals correctly:

import inflect
p = inflect.engine()
print("You have {}.".format(p.no('message',num_messages)))

Which would output strings like

You have no messages.
You have 1 message.
You have 34 messages.
David Dean
  • 7,435
  • 6
  • 33
  • 41
0

You can use condition or ternary operator to handle the issue but looking it differently, we often display plural / singular words in the following manner

1 view(s), 1 day(s) left, or 1 answer(s)  

This is often useful when adding condition may not be straightforward, example as an input field?

As for Python, you can create a function to perform the repetitive task of comparing and adding an extra 's' for you

>>> def pluralize(n, text):
    return "{} {}{}".format(n,text, 's' if n > 1 else '')

>>> pluralize(3,'word')
'3 words'
>>> pluralize(1,'word')
'1 word'
Abhijit
  • 62,056
  • 18
  • 131
  • 204