How might I create an acronym by splitting a string at the spaces, taking the character indexed at 0, joining it together, and capitalizing it?

TimeWillTell picture TimeWillTell · May 19, 2014 · Viewed 7.5k times · Source

My code

beginning = input("What would you like to acronymize? : ")

second = beginning.upper()

third = second.split()

fourth = "".join(third[0])

print(fourth)

I can't seem to figure out what I'm missing. The code is supposed to the the phrase the user inputs, put it all in caps, split it into words, join the first character of each word together, and print it. I feel like there should be a loop somewhere, but I'm not entirely sure if that's right or where to put it.

Answer

Dietrich Epp picture Dietrich Epp · May 19, 2014

Say input is "Federal Bureau of Agencies"

Typing third[0] gives you the first element of the split, which is "Federal". You want the first element of each element in the sprit. Use a generator comprehension or list comprehension to apply [0] to each item in the list:

val = input("What would you like to acronymize? ")
print("".join(word[0] for word in val.upper().split()))

In Python, it would not be idiomatic to use an explicit loop here. Generator comprehensions are shorter and easier to read, and do not require the use of an explicit accumulator variable.