-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?

DYZ
  • 55,249
  • 10
  • 64
  • 93
Daniel Segal
  • 87
  • 3
  • 9

4 Answers4

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.

DYZ
  • 55,249
  • 10
  • 64
  • 93
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')
mad_
  • 8,121
  • 2
  • 25
  • 40
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
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
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)

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179