[find a string between 2 strings]

This is the place for queries that don't fit in any of the other categories.

[find a string between 2 strings]

Postby ggd » Tue Jan 14, 2014 3:55 pm

Hi all,

and thanks for your help.
I am new in python. My first code began yesterday...

I get a string like this

Code: Select all
       Life is good in France. It is sunny today!
       Tomorrow what the weather like?
       I have written my example...


I would like to only return text between "good in" and "have written"
How can I do that?

I've tryed with
re.findall("Life is good in(.+)have written")
But it returns:

Code: Select all
       France. It is sunny today!
       Tomorrow what the weather like?
       I have written my example...
Last edited by metulburr on Tue Jan 14, 2014 3:58 pm, edited 1 time in total.
Reason: initial lock and added code tags
ggd
 
Posts: 1
Joined: Tue Jan 14, 2014 3:38 pm

Re: [find a string between 2 strings]

Postby metulburr » Tue Jan 14, 2014 4:12 pm

I would like to only return text between "good in" and "have written"
How can I do that?

If you can avoid using re then do it.

If you know the starting and ending text
Code: Select all
lines = '''Life is good in France. It is sunny today!
Tomorrow what the weather like?
I have written my example...
'''

start = lines.find(' It is sunny')
end = lines.find('have written')
print(lines[start:end])



If you dont know the starting and ending text
Code: Select all
lines = '''Life is good in France. It is sunny today!
Tomorrow what the weather like?
I have written my example...
'''

start_search = 'France.'
end_search = '\nI'

start = lines.find(start_search)
end = lines.find(end_search)

new_start = start+len(start_search)
new_end = end+len(end_search)

print(lines[new_start:new_end])



---output---
Code: Select all
 It is sunny today!
Tomorrow what the weather like?
I
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1312
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 3 guests