-1

ok, so lets say I have

s = 'ABC Here DEF GHI toHere JKL'

and I want to get a new string with only the string between Here and toHere

new_str = 'DEF GHI'

(I dont know how many or which chars I have before Here or any where else) I just know that I have Here and toHere in the string. how can I get the new_str?

1
  • 1
    import re;print(re.findall("Here(.*)toHere",target_string)) ... I guess Commented Oct 10, 2018 at 19:14

4 Answers 4

5

The simplest way is to use slicing:

s[s.find('Here') + len('Here') : s.find('toHere')]
#' DEF GHI '

You can .strip() off the white space from the result if you want.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot! thats what I have been searching for
1

This might be useful using index

str1 = 'ABC Here DEF GHI toHere JKL' 
try:
    start=str1.index('Here')+len('Here')
    end=str1.index('toHere')

    print(str1[start:end].strip())
except ValueError:
    print('Either of the substring not found')

Comments

0

You can use enumerate and .split() to grab the proper indexes for your new slice, then ' '.join() that new slice

s = 'ABC Here DEF GHI toHere JKL'
s = s.split()
for i, v in enumerate(s):
    if v == 'Here':
        start = i + 1
    if v == 'toHere':
        end = i
print(' '.join(s[start:end]))
# DEF GHI

Comments

0

the simplest way is to use splitting (imho)

print(s.split("Here",1)[-1].split("toHere",1)[0])

of coarse if Here is not present or toHere is not present it will not work how you expect (it will suffer the same consequences as the other solutions)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.