Creating acronyms in Python

If you want to use capitals only

>>>line = ' What AboutMe '
>>>filter(str.isupper, line)
'WAM'

What about words that may not be Leading Caps.

>>>line = ' What is Up '
>>>''.join(w[0].upper() for w in line.split())
'WIU'

What about only the Caps words.

>>>line = ' GNU is Not Unix '
>>>''.join(w[0] for w in line.split() if w[0].isupper())
'GNU'

Without re:

>>> names = 'Vincent Vega Jules Winnfield'
>>> ''.join(x[0] for x in names.split())
'VVJW'

If you want to do things the way that is grammatically correct (regardless of locale), use title(), then filter():

acronym = filter(str.isupper, my_string.title())

title() is pretty awesome; it makes a string titlecased and is correct according to locale.


Try

print "".join(e[0] for e in x.split())

Your loop actually loops over all characters in the string x. If you would like to loop over the words, you can use x.split().

Tags:

Python