Acronym in Python

An acronym is formed by taking the first letter of each word in a phrase. In Python, we can create acronyms by splitting the phrase into words and extracting the first character of each word, excluding common words like "and".

Problem Statement

Given a string representing a phrase, we need to generate its acronym. The acronym should be capitalized and exclude the word "and".

For example, if the input is "Indian Space Research Organisation", the output should be "ISRO".

Algorithm

To solve this problem, we follow these steps ?

  • Split the string into individual words

  • Initialize an empty string to store the acronym

  • For each word in the phrase:

    • If the word is not "and", take its first letter

    • Append the first letter to our acronym string

  • Convert the final string to uppercase and return it

Example

Here's the implementation of the acronym generator ?

class Solution:
    def solve(self, s):
        tokens = s.split()
        acronym = ""
        for word in tokens:
            if word != "and":
                acronym += word[0]
        return acronym.upper()

# Test the solution
ob = Solution()
result = ob.solve("Indian Space Research Organisation")
print(result)
ISRO

Alternative Approach Using List Comprehension

We can make the code more concise using list comprehension ?

def create_acronym(phrase):
    words = phrase.split()
    acronym = ''.join([word[0] for word in words if word.lower() != "and"])
    return acronym.upper()

# Test with multiple examples
phrases = [
    "Indian Space Research Organisation",
    "National Aeronautics and Space Administration",
    "World Health Organization"
]

for phrase in phrases:
    print(f"'{phrase}' ? {create_acronym(phrase)}")
'Indian Space Research Organisation' ? ISRO
'National Aeronautics and Space Administration' ? NASA
'World Health Organization' ? WHO

Handling Case Sensitivity

To make the solution more robust, we should handle "and" in different cases ?

def create_acronym_robust(phrase):
    words = phrase.split()
    acronym = ""
    for word in words:
        if word.lower() not in ["and", "&"]:
            acronym += word[0]
    return acronym.upper()

# Test with different cases
test_phrase = "Research and Development"
print(f"'{test_phrase}' ? {create_acronym_robust(test_phrase)}")

test_phrase2 = "Research AND Development"  
print(f"'{test_phrase2}' ? {create_acronym_robust(test_phrase2)}")
'Research and Development' ? RD
'Research AND Development' ? RD

Conclusion

Creating acronyms in Python is straightforward using string methods like split() and upper(). The key is to filter out common words like "and" while collecting the first letter of each meaningful word.

Updated on: 2026-03-25T10:11:40+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements