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
?
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.
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.
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.
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()
.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With