How to make a function shorter

Viewed 83

I have this function which works but I am trying to make it as short as possible. Something like: return [result(result += word[0]) for word in text]. Basically in one line, but it doesn't seem to work.

def first_letter(text):
    text = text.upper().split()
    result = ''
    for word in text:
        result += word[0]
    return result
2 Answers
def first_letter(text):
    return "".join([word[0] for word in text.upper().split()])

Can be even shorter (ignoring the import statement) using regex substitution.

import re
def first_letter(text):
  return re.sub(r"(\S)\w*\s*", r"\1", text.upper())
Related