Kbyte(s) eliminator

TrustyTony 0 Tallied Votes 759 Views Share

As I was student, the bracketed plurals were absolute 'NO, NO'.
With this simple function you can cleanly avoid putting bracket plural(s) after your numbers.

If the number deciding singular/plural should not be automatically included, you can make version with str(n)+' '+ eliminated. If you want to put automatically space separator around the expression, you can add that also. You can also put here number to words routine for small integers for "one apple" and "ten apples".

P.S. In Finnish this is more useful still as we have various partitive form after number:

>>> plural(5,'koira','koiraa')
'5 koiraa'
>>> plural(4,'neulanen','neulasta')
'4 neulasta'
>>>

## You can add to this number to words converter if you like
def plural(n,sing,plur):
    if n-1: return str(n)+' '+plur
    return str(n)+' '+sing
""" Output
>>> for a in range(5): plural(a,'MByte','Mbytes')

'0 Mbytes'
'1 MByte'
'2 Mbytes'
'3 Mbytes'
'4 Mbytes'
>>> 
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In this case you can use the usual Python approach ...

# add an 's' to indicate plural when k is not 1
for k in range(5):
    print( "%s kilobyte%s" %  (k, 's'*(k != 1)) )
Beat_Slayer 17 Posting Pro in Training

Nice one vegaseat.

Thanks for the share.

TrustyTony 888 pyMod Team Colleague Featured Poster

Time has passed since writing this code and now as I have learned the conditional value statement I would write this:

'%i %s'  % (k,'kByte' if k==1 else 'kBytes')

this works with the Finnish example also and English 'man' and 'men'

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Thanks tony, that's probably the more Pythonic way to do it. Or staying with the old True=1, False=0 routine ...

# add plural word when k is not 1
for k in range(5):
    print( "%s %s" %  (k, ('man', 'men')[k != 1]) )
TrustyTony 888 pyMod Team Colleague Featured Poster

Nice hack, maybe not so supper readable though.

Here is then the new plural, tested to run with Python 2.7 and 3.1:

def plural(amount,sing,plur):
    return'%i %s' % (amount, sing if amount==1 else plur)

if __name__=='__main__':
    print(plural(1,'koira','koiraa'))
    print(plural(5,'koira','koiraa'))
    print(plural(1,'man','men'))
    print(plural(3,'man','men'))
    
"""Output:
1 koira
5 koiraa
1 man
3 men
"""

See related post http://www.daniweb.com/forums/post1271292.html#post1271292, for producing English plural words.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.