Home > database >  How to make a function shorter
How to make a function shorter

Time:11-06

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

CodePudding user response:

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

CodePudding user response:

If you want short approach you can use ''.join() like below:

def first_letter_2(text):
    return ''.join(map(lambda x: x[0].upper(), text.split()))

CodePudding user response:

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