How to extract a substring from a string in Python with find()?

Question:

I have a string in Python, and I need to extract a substring from it. The substring I need to extract is between two specific characters in the string. The string is of indeterminate length and value, so slicing at specific points does not work in this case. How can I achieve this?

For example, suppose I have the string "The quick brown fox jumps over the lazy dog". I want to extract the substring between the characters "q" and "o", which is "uick br". How can I do this using Python? I’ve tried using the find() function, but I’m not sure how to extract the substring once I’ve found the positions of the characters.

Asked By: xentoo

||

Answers:

If you sure there is at least one sub-string existing between two specified characters, it’s able to use regex functions, particularly search. The function returns a group of matches. You can pick one from the group or travel through the group and select ones as your needs.

Below is an example of finding a substring between two specified characters q and o.

str = "The quick brown fox jumps over the lazy dog"
sub = re.search("q(.+?)o",str).groups()[0]
print(sub)
Answered By: TaQuangTu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.