Domanda

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?

È stato utile?

Soluzione

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'); ?>

Altri suggerimenti

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.

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'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top