Skip to content

How to Remove a Prefix or Suffix from a String in Python

How to Remove a Prefix or Suffix from a String in Python

When working with strings in Python, you will often find yourself needing to remove a prefix or a suffix. For example, file names may be prefixed with a certain string and you want to remove that prefix when renaming files. Similarly, you may want to remove salutations, such as 'Mr.' from a name.

In this tutorial, you’ll learn how to remove a prefix or a suffix from a string in Python. There are a lot of different ways in which to handle this. Python 3.9 made it much easier with dedicated string methods. If you’re not using Python 3.9, however, don’t worry! This tutorial will provide you with a complete understanding of how to remove a prefix and suffix from a Python string!

By the end of this tutorial, you’ll have learned the following:

  • How to use Python to remove either a prefix or a suffix from a string using dedicated string methods
  • How to use string slicing to remove a prefix or a suffix

How to Remove a Prefix from a String in Python

What is the best way to remove a prefix from a string in Python?

If you are using Python 3.9 or later, the best way to remove a suffix from a string in Python is to use the .removeprefix() method. If you’re working with an older version of Python, the best way is to combine the .startswith() method with string slicing.

There are two general methods that can be used to remove a prefix from a Python string reliably. While there are many other methods floating around on the internet, my opinion is that they do not work reliably. Many of the other methods aren’t as intuitive or don’t work as reliably.

Let’s dive into how to remove a prefix using versions of Python 3.9 or later.

How to Remove a Prefix From a Python String Using removeprefix()

Python version 3.9 introduced a new string method, removeprefix(), which allows you to pass in a prefix that you want to remove.

The method was put into place due to behavior of other methods, such as .lstrip() leading to unexpected behavior. Python’s PEP 616 introduced this method to help clarify the behavior for many users.

Let’s take a look at how to remove a prefix using the str.removeprefix() method:

# Remove a String Prefix with str.removeprefix()
text = 'https://datagy.io'
without_prefix = text.removeprefix('https://')

print('Before: ', text)
print('After: ', without_prefix)

# Returns:
# Before:  https://datagy.io
# After:  datagy.io

We can see in the code block above that the string originally contained an https:// prefix. Using the str.removeprefix() method, we were able to pass in the string prefix that we wanted to remove.

Keep in mind that Python strings are immutable. In the example above, we assigned the string to a new variable. However, we could also simply assign the list back to itself.

How to Remove a Prefix From a Python String with String Slicing and startswith()

In versions of Python prior to version 3.9, the str.removeprefix() method wasn’t available. If you’re working with an older version of Python, you’ll need to find a different method to remove a prefix.

Under the hood, Python actually uses a very simple function to create the .removeprefix() method. We can simply recreate this method in order to remove a prefix in older versions of Python. Let’s take a look at how this method is written, by converting it into a standard function:

# Writing a Function To Remove a Prefix in Python
def removeprefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix):]
    else:
        return text

Let’s break down what the function above is doing:

  1. The function, removeprefix(), takes two arguments:
    1. The string we want to modify, and
    2. The prefix we want to remove
  2. We use the .startswith() method to check if the string starts with the prefix
  3. If it does, we slice the string from the first character following the prefix to the end of the string
  4. If not, we return the entire string

Now that you have a good understanding of how this function works, let’s see how we can use it to remove a prefix from a string in Python:

# Removing a Prefix from a String with a Custom Function
def removeprefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix):]
    else:
        return text

text = 'https://datagy.io'
new_text = removeprefix(text, 'https://')

print('Before: ', text)
print('After: ', new_text)

# Returns:
# Before:  https://datagy.io
# After:  datagy.io

In the code block above, we used our custom function to remove a prefix from a string. Keep in mind that this is actually the same function that Python uses under the hood. Because of this, we can be confident that it’s a safe and efficient way of removing a prefix.

Let’s now dive into how to remove a suffix from a string in Python.

How to Remove a Suffix from a String in Python

What is the best way to remove a suffix from a string in Python?

If you are using Python 3.9 or later, the best way to remove a suffix from a string in Python is to use the .removesuffix() method. If you’re working with an older version of Python, the best way is to combine the .endswith() method with string slicing.

There are two simple and straightforward ways to remove a suffix from a string. While there are countless different ways in you can accomplish this, these two ways represent safe, reliable, and efficient ways to remove a suffix.

How to Remove a Suffix From a Python String Using removesuffix()

Similar to the str.removeprefix() method, Python 3.9 introduced a new string method, removesuffix(), which is used to remove a suffix from a string. Because the str.rstrip() method led to unexpected behavior, Python introduced this method to simplify behavior.

Let’s see how we can use the removesuffix() method in Python:

# Remove a String Suffix with str.removeprefix()
text = 'datagy.io'
new_text = text.removesuffix('.io')

print('Before: ', text)
print('After: ', new_text)

# Returns:
# Before:  datagy.io
# After:  datagy

We can see how easy it was to remove a suffix with the removesuffix() string method. The method is clear and intentional – letting the reader of your code know exactly what it’s intended to do.

Because this method isn’t available in versions older than Python 3.9, you’ll need to use a different approach if you’re working with older versions.

How to Remove a Suffix From a Python String with String Slicing and endswith()

Similar to the .removeprefix() method, Python uses a very simple function to create the .removesuffix() method. We can simply recreate this method in order to remove a suffix from a string.

Let’s take a look at how this method is written, by converting it into a standard function:

# Writing a Function To Remove a Suffix in Python
def removesuffix(text, suffix):
    if text.endswith(suffix):
        return text[:-len(suffix)]
    else:
        return text

Let’s take a look at how the functin works, as it’s slightly different from our earlier function to remove a prefix:

  1. The function, removesuffix(), takes two arguments:
    1. The string we want to modify, and
    2. The suffix we want to remove
  2. We use the .endswith() method to check if the string ends with the suffix
  3. If it does, we slice the string from the beginning to the negative index of the length of the suffix
  4. If not, we return the entire string

Now that you have a good understanding of how this function works, let’s see how we can use it to remove a suffix from a string in Python:

# Removing a Suffix from a String with a Custom Function
def removesuffix(text, suffix):
    if text.endswith(suffix):
        return text[:-len(suffix)]
    else:
        return text


text = 'datagy.io'
new_text = removesuffix(text, '.io')

print('Before: ', text)
print('After: ', new_text)

# Returns:
# Before:  datagy.io
# After:  datagy

In the code block above, we used our custom function to remove a suffix from a string. Because this is the same method that Python uses under the hood, we can be confident that it’s a safe and efficient way of removing a prefix.

Conclusion

Being able to work with and manipulate strings in Python is an important skill. It has countless applications, from renaming files to cleaning text for analysis. In this tutorial, you learned how to remove a suffix or prefix from a string in Python.

You first learned how to remove a prefix, both using dedicated string methods and using custom functions. Then, you learned how to remove a suffix, again using a dedicated metho and a custom function. While other tutorials may show multiple different ways of accomplishing these tasks, these methods are either built-in or represent safe, consistent behavior.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

2 thoughts on “How to Remove a Prefix or Suffix from a String in Python”

Leave a Reply

Your email address will not be published. Required fields are marked *