How do I get a substring of a string in Python?

9    Asked by ShibataTakagi in Python , Asked on Apr 17, 2025

What methods or syntax does Python offer to get a substring from a larger string? Learn how slicing and indexing make it easy to handle substrings in Python.

To get a substring of a string in Python, the most common and Pythonic way is to use slicing. Python strings are sequences, which means you can access parts of them using slice notation. It's simple and efficient once you get the hang of it.

Here’s how you can do it:

 Using Slice Notation:

text = "Hello, World!"
substring = text[0:5] # This will give you 'Hello'

  • text[start:end]: extracts characters from index start to end-1
  • If start is omitted, it defaults to 0.
  • If end is omitted, it goes till the end of the string.

 Examples:

  • text[:5] → "Hello" (first 5 characters)
  • text[7:] → "World!" (from 7th character to end)
  • text[-6:-1] → "World" (negative indices work too)

 Things to Remember:

  • Indexing starts from 0.
  • Negative indices count from the end of the string.
  • If the end index is beyond the string length, it just returns up to the available characters—no error.

 Using String Methods (alternative way):

  • You can also use built-in string methods like .split(), .find(), or .replace() for more customized substring extraction.

Python doesn’t have a substring() function like some other languages, but slicing is powerful and flexible enough to handle most use cases. Once you get comfortable with indexing, you'll find slicing extremely useful for all kinds of string operations.



Your Answer

Interviews

Parent Categories