Python problem 5 of 30

Capitalise each word

  • Python
  • Easy

Write capitalise_words(s) that makes the first letter of every word upper case and leaves the rest of each word as it is. Words are separated by spaces.

capitalise_words("hello wide world")
# "Hello Wide World"

capitalise_words("they're here")
# "They're Here"
Show hint

Try "they're here".title() first and look closely at the result. Then build each word yourself from w[:1].upper() and w[1:].

Show solution
def capitalise_words(s):
    return " ".join(w[:1].upper() + w[1:] for w in s.split(" "))

str.title() treats an apostrophe as the end of a word, so it gives "They'Re Here". Building each word by hand avoids that. w[:1] is safe on empty strings (unlike w[0]), and splitting on " " rather than any whitespace keeps the original spacing.

Want a problem like this every day? See today's problem and keep a streak going.