Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating acronyms in Python

Tags:

python

In Python, how do I make an acronym of a given string?

Like, input string:

'First Second Third'

Output:

'FST'

I am trying something like:

>>> for e in x:
        print e[0]

But it is not working... Any suggestions on how this can be done? I am sure there is a proper way of doing this but I can't seem to figure it out. Do I have to use re?

like image 681
user225312 Avatar asked Dec 04 '10 18:12

user225312


People also ask

What do you mean by acronyms in python?

Suppose we have a string s that is representing a phrase, we have to find its acronym. The acronyms should be capitalized and should not include the word "and". So, if the input is like "Indian Space Research Organisation", then the output will be ISRO.

How do you create an acronym?

Style guides suggest that you write the acronym first, followed by the full name or phrase in parentheses. You can also write them in the opposite order—whatever makes more sense. In short, if the acronym is more widely known, list it first; if it's more obscure, you may want to start with the entire phrase.

How do you print abbreviations in Python?

fullname(str1) /* str1 is a string */ Step 1: first we split the string into a list. Step 2: newspace is initialized by a space(“”) Step 3: then traverse the list till the second last word. Step 4: then adds the capital first character using the upper function. Step 5: then get the last item of the list.


2 Answers

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().

like image 131
Sven Marnach Avatar answered Oct 13 '22 01:10

Sven Marnach


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'
like image 37
kevpie Avatar answered Oct 13 '22 01:10

kevpie