VOOZH about

URL: https://www.geeksforgeeks.org/python/python-string-till-substring/

⇱ Python - String till Substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - String till Substring

Last Updated : 12 Jul, 2025

When working with Python strings, we may encounter a situation where we need to extract a portion of a string that starts from the beginning and stops just before a specific substring. Let's discuss certain ways in which we can do this.

Using split()

The split() method is a simple and efficient way to extract the part of a string before a specific substring. By splitting the string at the substring and taking the first part, we can achieve the desired result.


Output
learn

Explanation:

  • We define the string 's' and the substring 'sub'.
  • The split() method splits the string 's' at every occurrence of 'sub'.
  • We take the first part of the split result using [0].

Let's explore some more methods to split a string up to a specific substring.

Using find() and slicing

The find() method allows us to locate the position of the substring within the string. Once we have the index, we can slice the string up to that position.


Output
learn

Explanation:

  • We use find() to locate the position of the substring 'sub' in the string 's'.
  • The string is then sliced from the beginning up to the index of sub using s[:idx].

Using partition()

The partition() method splits the string into three parts: the portion before the substring, the substring itself, and the portion after the substring. We only need the first part.


Output
learn

Explanation:

  • The partition() method splits the string into three parts based on the substring sub.
  • We take the first part of the result using [0].

Using regular expressions

The re.split() method can be used to split the string at the substring and extract the first part.


Output
learn

Explanation:

  • We import the re module and define the string 's' and the substring 'sub'.
  • The re.split() method splits the string at the substring, and we take the first part using [0].

Using a loop

We can manually iterate through the string and stop when we encounter the substring.


Output
learn

Explanation:

  • We initialize an empty string res to store the result.
  • Using a for loop, we iterate through each character in 's'.
  • If we encounter the substring, we break the loop; otherwise, we add characters to res.
Comment