To remove a specific substring in a string variable in Python, the easiest way is to use the Python string replace() function.

s = "This is a string."

string_without_substring = s.replace("is","")

print(string_without_substring)

#Output:
This  a string.

When working with strings in Python, being able to manipulate your variables easily is important. There are a number of built in string methods which allow us to get information and change string variables.

One such function which is very useful is the string replace() function. With the replace() function, we can create a new string where the specified value is replaced by another specified value.

replace() takes a string to search for and a replacement value and replacing all found strings with the replacement value.

To remove a given substring from a string, you can use replace() and pass the substring as the search value and an empty string as the replacement value as shown below.

s = "This is a string."

string_without_substring = s.replace("is","")

print(string_without_substring)

#Output:
This  a string.

Using the replace() function to Make Replacements in Strings in Python

You can use replace() for many other cases in your Python programs.

For example, if we want to replace spaces with dashes, we can do the following.

string_with_spaces = "This is a string."

string_with_dashes = string_with_spaces.replace(" ","-")

print(string_with_dashes)

#Output:
This-is-a-string.

If we want to replace all the spaces with periods, we can do so easily in the following Python code.

string_with_spaces = "This is a string."

string_with_periods = string_with_spaces.replace(" ","-")

print(string_with_periods)

#Output:
This.is.a.string.

Hopefully this article has been useful for you to learn how to remove a substring from a string in Python.

Categorized in:

Python,

Last Update: March 11, 2024