Python – Separate last sentence from string in a list

Question:

I have a string like

x = 'Test. Test1. Test test test.'

Now I would like to separate the last sentence (meaning the last set of strings that start with a capital letter) from the rest of the strings in a list. How’s that possible?

Asked By: Frigoooo

||

Answers:

IIUC, You can use re.split base capital chars and return two last elements of result.

>>> import re
>>> x = 'Test. Test1. Test test test.'

>>> re.split(r'([A-Z])', x)
['', 'T', 'est. ', 'T', 'est1. ', 'T', 'est test test.']
# you want this : ----------------^^^ and ^^^^^^^^^^^^^

>>> re.split(r'([A-Z])', x)[-2:]
['T', 'est test test.']

>>> ''.join(re.split(r'([A-Z])', x)[-2:])
'Test test test.'

Explanation:

  • [A-Z] : which allows any upper case letter between : (A-Z) -> A,B, …, X, Y, Z
Answered By: I'mahdi
x = 'Test. Test1. Test test test.'

separated = x[13:]

print(separated)

You can use an index from where you want the sentence to start, leaving no value after the colon means "until the end". If you need more conditions such as "from a capital letter", then the other answer may be more suited

Answered By: Conor

You can use the regex [A-Z][^A-Z]*$ to fetch that.
Example:

import re
s='Test. Test1. Test test test.'
last_sentence=re.findall('[A-Z][^A-Z]*$',s)
print(last_sentence)

Output:

['Test test test.']
Answered By: Liju
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.