emily
emily

Reputation: 29

How to make a function shorter

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

Upvotes: 1

Views: 444

Answers (2)

Shanavas M
Shanavas M

Reputation: 1629

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())

Upvotes: 0

DSteman
DSteman

Reputation: 1658

def first_letter(text):
    return "".join([word[0] for word in text.upper().split()])

Upvotes: 2

Related Questions