Problem overview
The method initials receives a full name, fullName, made of a first name and a last name separated by a single space. It returns the first letter of each name, in upper case, glued together. The initials are upper case even when the name is written in lower case. Both names contain English letters only.
For "grace hopper" the result is "GH". For "Ada Lovelace" it is "AL", since those letters are already upper case. For "a b" it is "AB": a name can be a single letter, and that letter is its initial.
Approach
There are two jobs: find the two words, then take the first letter of each. The string method split cuts the name at the space and returns a list of words. A word is a string, so its first letter is the character at index 0. Two indexes in a row do both jobs: the first picks the word from the list and the second picks the character from that word. Finally upper() turns the letters into capitals.
Step by step
- Split at the space.
fullName.split(" ")returns a list, stored here aswords. For"grace hopper"it is['grace', 'hopper']. With exactly one space there are exactly two items. - Take the first letter of each word.
words[0][0]is'g':words[0]is'grace'and the second[0]is its first character.words[1][0]is'h'. - Join them and make them upper case. The sum
words[0][0] + words[1][0]is'gh'. Put it in parentheses and callupper()on the whole thing to get'GH'.
The solution in Python
class Solution:
def initials(self, fullName: str) -> str:
words = fullName.split(" ")
return (words[0][0] + words[1][0]).upper()
Some details worth knowing:
- The parentheses matter.
words[0][0] + words[1][0].upper()would only capitalise the second letter, giving'gH'for"grace hopper". A method call binds to the value right before the dot, so the parentheses makeupper()apply to the joined pair. - Strings are immutable, so
upper()returns a new string and doesn't change the one it is called on. upper()leaves letters that are already upper case as they are, which is why"Ada Lovelace"still works.- Another way is to upper-case each letter separately:
words[0][0].upper() + words[1][0].upper()gives the same result.
Edge cases and common mistakes
- Single-letter names.
"a b"splits into['a', 'b'], and each word's first character is the whole word. The result is"AB". - Split with no argument.
split()cuts at any run of white space. For a name with a single space it gives the same list assplit(" "), and the lesson's steps usesplit(" "). - Extra spaces. The constraints promise exactly one. With two spaces,
split(" ")returns an empty string between the names, as in['ada', '', 'lovelace'], and index1would no longer be the last name. - Indexing a word with the wrong number.
words[0]is the whole first name. You need the second index,words[0][0], to get a single letter. - Forgetting to capitalise. For
"grace hopper"the answer is"GH", not"gh".
Testing
"grace hopper"gives"GH"."Ada Lovelace"gives"AL"."a b"gives"AB".
