In this article, we will see how to trim the string before a specific character. We will see some of the best approaches we can use to return the substring before the specific character.

We can achieve this efficiently by using the following in-built Python functions.

  1. split
  2. partition

Using split():

One of the best ways to trim a string before a specific character is by using the split() method. When we use the split(), the string gets split into the list of substrings based on the given delimiters. In the 0th index of the resultant array, we can get the substring which is present before the character we specified.

Following is the example:

string = "Hello, world! This is an example."
delimiter = ","
trimmed_string = string.split(delimiter)[0]
print(trimmed_string)

In the above example, the split function splits the string using the comma as a delimiter. The resultant list contains two elements where the 0th index contains “Hello” and the 1st index contains “world!“. By selecting the first element using [0], we trim the string before the command and get the output “Hello“.

Using partition():

The partition method splits the string into three parts:

  1. The substring before the first occurrence of the delimiter
  2. The delimiter itself
  3. The substring after the delimiter

In the result array, by selecting the 0th index we will get the desired output.

string = "Hello, world! This is an example."
delimiter = ","
trimmed_string = string.partition(delimiter)[0]
print(trimmed_string)

In the above example, the string.partition returns the list with three values i.e. “Hello“, “,” and “world! This is an example.“. By selecting the first part ([0]), we trim the string before the comma, resulting in the output “Hello”.

Categorized in:

Tagged in: