Home > Software engineering >  How to extract first letter of every nth word in a sentence?
How to extract first letter of every nth word in a sentence?

Time:12-20

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

CodePudding user response:

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.

CodePudding user response:

I don't know how did you solve the first part and can not solve the second one,
but anyway, strings in python are simply a list of characters, so if you want to access the 1st character you get the 0th index. so applying that to your example, as the comment mentioned you type (word[0]),

so you can print the word[0] or maybe collect the 1st characters in a list to do any further operations (I do believe that what you want to do, not just printing them!)

def extract(text):
    mychars=[]
    for word in text.split()[::5]:
        mychars.append(word[0])
    print(mychars)

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

CodePudding user response:

The below code might help you out. Just an example idea based on what you said.

 #
 # str Text   : A string of words, such as a sentence.
 # int split  : Split the string every nth word 
 # int maxLen : Max number of chars extracted from beginning of each word
 #

 def extract(text,split,maxLen):
     newWord = ""
     # Every nth word
     for word in text.split()[::split]:
         if len(word) < maxLen:
              newWord  = word[0:] #Entire word (if maxLength is small)
         else:
              newWord  = word[:maxLen] #Beginning of word until nth letter
     return (None if newWord=="" else newWord) 

 text = "The quick brown fox jumps over the lazy dog."

 result = extract(text, split=5, maxLen=2) #Use split=5, maxLen=1 to do what you said specifically

 if (result):
      print (result) #Expected output: "Thov"
  • Related