How to Get a Substring in Python

`”banana”.find(“pear”)` returns `-1` when the text is absent. I’m fascinated that a failed search has a clear result, while `-1` can still act as a valid slice position.

You can separate the idea of a text fragment from the operation used to locate one. You’ll connect “substring” to a contiguous stretch of text and see how its positions are represented in Python.

What a substring means in Python

A substring is a contiguous run of text selected from a larger string, and Python represents strings as immutable sequences of Unicode code points.

Python’s str documentation