PythonMastery

Acronym generator in Python

Build an acronym from the first letter of each word, such as Portable Network Graphics to PNG, skipping small words like of and the.

An acronym is made from the first letter of each word: "as soon as possible" becomes ASAP. Real acronyms usually skip small words such as "of" and "the", so this program does the same.

The program

python
SMALL_WORDS = {"of", "and", "the", "for", "in", "a", "an"}


def make_acronym(phrase):
    words = phrase.replace("-", " ").split()
    return "".join(word[0].upper() for word in words if word.lower() not in SMALL_WORDS)


phrases = [
    "as soon as possible",
    "Portable Network Graphics",
    "Federal Bureau of Investigation",
    "self-contained underwater breathing apparatus",
    "  graphics   processing unit ",
    "",
]
for phrase in phrases:
    print(f"{phrase!r} -> {make_acronym(phrase)!r}")
output
'as soon as possible' -> 'ASAP'
'Portable Network Graphics' -> 'PNG'
'Federal Bureau of Investigation' -> 'FBI'
'self-contained underwater breathing apparatus' -> 'SCUBA'
'  graphics   processing unit ' -> 'GPU'
'' -> ''

How it works

Try changing it

Not every acronym skips small words. "as soon as possible" keeps both "as" words because they are not in the set. If you remove "and" from SMALL_WORDS, then "Research and Development" gives RAD instead of RD. Which words to skip depends on the acronyms you want to make.

Learn the idea: Working with Strings, Comprehensions: Lists, Dicts, Sets, Generators