Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract first letter of every nth word in a sentence?

I was trying to extract the first letter of every 5th word and after doing a bit of research I was able to figure out how to obtain every 5th word. But, how do I know extract the first letters of every 5th word and put them together to make a word out of them. This is my progress so far:

def extract(text):
    for word in text.split()[::5]:
        print(word)

extract("I like to jump on trees when I am bored")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As the comment pointed out, split it and then just access the first character:

def extract(text):
    for word in text.split(" "):
        print(word[0])

text.split(" ") returns an array and we are looping through that array. word is the current entry (string) in that array. Now, in python you can access the first character of a string in typical array notation. Therefore, word[0] returns the first character of that word, word[-1] would return the last character of that word.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading