top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

Acronym Generator in Python

The acronym is a word (such as NATO, radar, or laser) formed from the initial letter or letters of each of the successive parts or major parts of a compound term.


Let's generate an acronym in python.


First, define function.


def acronym(letter):
    lst = letter.split(" ")
    if len(lst) < 3:
        return("Letter should be 3 or more words.")
    else:
        first_words = [i[0] for i in lst if i not in ['of','on','as']]
        return(f"Acronym for '{letter}' is '{''.join(first_words).upper()}'")

- The Second-line of code is to split the letters at spaces.

- Then, if the length of the letter is less than 3, it will return "Letter should be 3 or more words.

- If the length of the letter is 3 or more, from the list of each word, preposition words are removed and take the first character and append to list named 'first_words'. Words that want to be removed, can add as you wish.

- Then join each word from the list and make them into uppercase.

Let's see the results.


print(acronym("north atlantic treaty organization"))
> Acronym for 'north atlantic treaty organization' is 'NATO'

print(acronym("united states of america"))
> Acronym for 'united states of america' is 'USA'

print(acronym("machine learning"))
> Letter should be 3 or more words.


Yes, it works. That's all.

Here's my GitHub link for that.




7 comments

Recent Posts

See All

7 Comments


Data Insight
Data Insight
Sep 03, 2021

Actually you don't need to test for the len of 'letter'. Just check for the len of i in your for loop and make sure it is not less than 3. In this case you are assuming that prepositions are most one or two letter words.

Like

Data Insight
Data Insight
Sep 03, 2021

Nice! What part of the code ignores prepositions?

Like
Data Insight
Data Insight
Sep 03, 2021
Replying to

Nice improvement to the code!

Like
bottom of page