-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
  • 51,549
  • 10
  • 60
  • 87
Daniel Segal
  • 57
  • 3
  • 8

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
  • 51,549
  • 10
  • 60
  • 87
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_
  • 7,844
  • 2
  • 22
  • 37
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,449
  • 1
  • 6
  • 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
  • 103,130
  • 11
  • 146
  • 174