fork download
  1. import re
  2.  
  3. text = 'the house is big the house is big the house is big'
  4. char_nr = 19
  5. pattern = rf"\S.{{0,{char_nr - 1}}}(?!\S)"
  6.  
  7. strings = re.findall(pattern, text)
  8.  
  9. print(strings)
  10.  
  11. list_of_words_before = strings[1].split()
  12. print(list_of_words_before)
  13.  
  14. nr_words = 3
  15. lenOfWordsBefore = len(list_of_words_before)
  16. if nr_words > lenOfWordsBefore:
  17. nr_words = lenOfWordsBefore
  18.  
  19. print(list_of_words_before[-nr_words:])
Success #stdin #stdout 0.03s 9536KB
stdin
Standard input is empty
stdout
['the house is big', 'the house is big', 'the house is big']
['the', 'house', 'is', 'big']
['house', 'is', 'big']