-4

I need to write a function that returns the first letters (and make it uppercase) of any text like:

shortened = shorten("Don't repeat yourself")
print(shortened)

Expected output:

DRY

and:

shortened = shorten("All terrain armoured transport")
print(shortened)

Expected output:

ATAT
cs95
  • 379,657
  • 97
  • 704
  • 746
Ribote
  • 3
  • 1

3 Answers3

0

Use list comprehension and join

shortened = "".join([x[0] for x in text.title().split(' ') if x])
Valeriy Gaydar
  • 500
  • 1
  • 6
  • 26
-1

Using regex you can match all characters except the first letter of each word, replace them with an empty string to remove them, then capitalize the resulting string:

import re

def shorten(sentence):
    return re.sub(r"\B[\S]+\s*","",sentence).upper()

print(shorten("Don't repeat yourself"))

Output:

DRY
glhr
  • 4,439
  • 1
  • 15
  • 26
-1
text = 'this is a test'
output = ''.join(char[0] for char in text.title().split(' '))
print(output)

TIAT

Let me explain how this works.

My first step is to capitalize the first letter of each work

text.title()

Now I want to be able to separate each word by the space in between, this will become a list

text.title()split(' ')

With that I'd end up with 'This','Is','A','Test' so now I obviously only want the first character of each word in the list

for word in text.title()split(' '): print(word[0]) # T I A T

Now I can lump all that into something called list comprehension

output = [char[0] for char in text.title().split(' ')]
# ['T','I','A','T']

I can use ''.join() to combine them together, I don't need the [] brackets anymore because it doesn't need to be a list

output = ''.join(char[0] for char in text.title().split(' ')
Ari
  • 5,301
  • 8
  • 46
  • 120