-3

I'd like to know how to find characters in between texts in python. What I mean is that you have for example:

cool_string = "I am a very cool string here is something: not cool 8+8 that's it"

and I want to save to another string everything in between something: to that's it. So the result would be:

soultion_to_cool_string = ' not cool 8+8 '
Jan
  • 17
  • 4
  • `cool_string[cool_string.index(':')+1: cool_string.index("that's it")]` – James Jan 22 '22 at 22:41
  • Jame's slice approach or look into Python's `.splt()` string method. For more advanced parsing, you may want to eventually look into regular expressions but the current version should not require it. – Wayne Jan 22 '22 at 22:42

2 Answers2

0

You can use str.find()

start = "something:"
end = "that's it"

cool_string[cool_string.find(start) + len(start):cool_string.find(end)]

If you need to remove empty space str.strip()

Andrea Di Iura
  • 467
  • 5
  • 11
0

You should look into regex it will do your job. https://docs.python.org/3/howto/regex.html

Now for your question we will first require the lookahead and lookbehind expressions

The lookahead:

Asserts that what immediately follows the current position in the string is foo.

Syntax: (?=foo)

The lookbehind:

Asserts that what immediately precedes the current position in the string is foo.

Syntax: (?<=foo)

We need to look behind for something: and lookahead for that's it

import re
regex = r"(?<=something:).*?(?=that\'s it)"  # .*? is way to capture everything in b/w except line terminators
re.findall(regex, cool_string)
Ibrahim
  • 798
  • 6
  • 26