python - Find the first word of a paragraph inside a list -


i have created list contains different paragraph inside each element.

i want find first word of each paragraph.

the thing can come split each paragraph in individual words , find element[0]. seems excessive have each paragraph in list

so better way this?

something this?

l = ['start of paragraph 1','start of paragraph 2','para 3'] first_words = [p.split()[0] p in l] print first_words 

prints: ['start', 'start', 'para']

if don't want split each paragraph, search index of first space, , grab each word that:

l = ['start of paragraph 1','start of paragraph 2','para 3'] first_words = [p[:p.find(' ')] p in l] print first_words 

prints: ['start', 'start', 'para']

explanation requested:

  • find first space in paragraph p.find(' ') - returns position
  • then take first characters in paragraph via p[:p.find(' ')]
  • the remainder of line called list comprehension , loops through list , takes each paragraph, p in turn

Comments