Open In App

Python – Create acronyms from words

Given a string, the task is to write a Python program to extract the acronym from that string.

Examples:



Input: Computer Science Engineering

Output: CSE



Input: geeks for geeks

Output: GFG

Input: Uttar pradesh

Output: UP

Approach 1:

The following steps are required:




# function to create acronym
def fxn(stng):
   
    # add first letter
    oupt = stng[0]
     
    # iterate over string
    for i in range(1, len(stng)):
        if stng[i-1] == ' ':
           
            # add letter next to space
            oupt += stng[i]
             
    # uppercase oupt
    oupt = oupt.upper()
    return oupt
 
 
# input string
inpt1 = "Computer Science Engineering"
 
# output acronym
print(fxn(inpt1))
 
# input string
inpt1 = "geeks for geeks"
 
# output acronym
print(fxn(inpt1))
 
# input string
inpt1 = "Uttar pradesh"
 
# output acronym
print(fxn(inpt1))

Output:

CSE
GFG
UP

Time Complexity: O(n) -> looping once through string of length n.

Space Complexity: O(n) -> as space is required for storing individual characters of a string of length n.

Approach 2:

The following steps are required:




# function to create acronym
def fxn(stng):
   
    # get all words
    lst = stng.split()
    oupt = ""
     
    # iterate over words
    for word in lst:
       
        # get first letter of each word
        oupt += word[0]
         
    # uppercase oupt
    oupt = oupt.upper()
    return oupt
 
 
# input string
inpt1 = "Computer Science Engineering"
 
# output acronym
print(fxn(inpt1))
 
# input string
inpt1 = "geeks for geeks"
 
# output acronym
print(fxn(inpt1))
 
# input string
inpt1 = "Uttar pradesh"
 
# output acronym
print(fxn(inpt1))

Output:

CSE
GFG
UP

Time Complexity: O(n) -> looping once through an array of length n.

Space Complexity: O(n) -> as space is required for storing individual characters of a string and an array of length n.

Approach 3: Using regex and reduce()

Here’s one approach using regular expressions (regex) to extract the first letter of each word and reduce function to concatenate them:




import re
from functools import reduce
 
def fxn(stng):
    words = re.findall(r'\b\w', stng)
    acronym = reduce(lambda x, y: x + y, [word[0].upper() for word in words])
    return acronym
 
# input string
inpt1 = "Computer Science Engineering"
  
# output acronym
print(fxn(inpt1))
  
# input string
inpt1 = "geeks for geeks"
  
# output acronym
print(fxn(inpt1))
  
# input string
inpt1 = "Uttar pradesh"
  
# output acronym
print(fxn(inpt1))

Output
CSE
GFG
UP

Time Complexity: O(n) -> looping once through an array of length n.

Auxiliary Space: O(n) -> as space is required for storing individual characters of a string and an array of length n.


Article Tags :