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
phrase.replace("-", " ")turns a hyphen into a space, so "self-contained" counts as two words.split()with no argument splits on any run of spaces and ignores spaces at the start and end. That is why the phrase with extra spaces still works, and why the empty string gives no words and an empty acronym.word[0].upper()takes the first letter and makes it a capital.if word.lower() not in SMALL_WORDSskips the small words. A set is used forSMALL_WORDSbecause checkinginon a set is fast, however many words it holds.!rin the f-string prints the string with its quotes, so you can see the spaces and the empty string.
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.