0

Here is the sample text.

sample_text='Extract text before the last word'

Using string split method I can extract substring before 'word'

print(sample_text.split('word',1)[0])

I am extracting sample_text from a pdf document so there can be following possibilities.

sample_text='Extract text before the last w ord'
sample_text='Extract text before the last wo rd'
sample_text='Extract text before the last wor d'
sample_text='Extract text before the last wo r d'

Is there a simple way to take these possibilities into account and get the desired output?

Thanks in advance.

asked Apr 21, 2020 at 7:27

2 Answers 2

1

You can use a regular expression that ignore space : In your example, with the word "word" that would be the regular expression :

"w\s*o\s*r\s*d"

Try to split each line in this way :

import re
sample_text='Extract text before the last w ord'
re_ignor_space = "w\s*o\s*r\s*d"
sample_text_splitted = re.split(re_ignor_space, sample_text)
desired_string = ''.join(sample_text_splitted[:-1])
print (desired_string)

If you do not need the last word just ignore it with slice :

desired_string = ''.join(sample_text_splitted[:-1])

Output :

Extract text before the last
answered Apr 21, 2020 at 7:39
Sign up to request clarification or add additional context in comments.

4 Comments

I don't need the last word. Expected output is:- 'Extract text before the last'
I added another line of code to get you the 'Extract text before the last' Check it out
Desired string still has 'w ord'
Okay i change the code and it should do the trick now...check it out
1

You can split by regex pattern if you want.


import re
pattern = 'w\d?o\d?r\d?d'
print(re.split(pattern, sample_text))

Outputs:

['Extract text before the last ', '']
answered Apr 21, 2020 at 7:29

2 Comments

It is still printing the entire sample_text.
Sorry, I had a typo in the pattern, try it now.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.