How to remove word from string python

I need to strip a specific word from a string.

But I find python strip method seems can’t recognize an ordered word. The just strip off any characters passed to the parameter.

For example:

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> papa.lstrip('papa')
" is a good man"
>>> app.lstrip('papa')
" is important"

How could I strip a specified word with python?

thefourtheye's user avatar

thefourtheye

231k52 gold badges451 silver badges494 bronze badges

asked May 15, 2014 at 3:59

Zen's user avatar

5

Use str.replace.

>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'

Alternatively use re and use regular expressions. This will allow the removal of leading/trailing spaces.

>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(s*)papa(s*)')
>>> patt.sub('\1mama\2', papa)
'mama is a good man'
>>> patt.sub('\1mama\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'

answered May 15, 2014 at 4:02

metatoaster's user avatar

metatoastermetatoaster

17k5 gold badges57 silver badges63 bronze badges

5

Easiest way would be to simply replace it with an empty string.

s = s.replace('papa', '')

answered May 15, 2014 at 4:02

iamdev's user avatar

iamdeviamdev

7064 silver badges13 bronze badges

3

If we’re talking about prefixes and suffixes and your version of Python is at least 3.9, then you can use these new methods:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'

answered Jan 26, 2022 at 14:20

qyryq's user avatar

qyryqqyryq

1502 silver badges6 bronze badges

If want to remove the word from only the start of the string, then you could do:

  string[string.startswith(prefix) and len(prefix):]  

Where string is your string variable and prefix is the prefix you want to remove from your string variable.

For example:

  >>> papa = "papa is a good man. papa is the best."  
  >>> prefix = 'papa'
  >>> papa[papa.startswith(prefix) and len(prefix):]
  ' is a good man. papa is the best.'

answered Feb 15, 2021 at 2:33

theQuestionMan's user avatar

theQuestionMantheQuestionMan

1,1512 gold badges15 silver badges28 bronze badges

You can also use a regexp with re.sub:

article_title_str = re.sub(r'(s?-?|?s?Times of India|s?-?|?s?the Times of India|s?-?|?s+?Gadgets No'',
                           article_title_str, flags=re.IGNORECASE)

bfontaine's user avatar

bfontaine

17.6k13 gold badges74 silver badges103 bronze badges

answered Feb 21, 2017 at 10:00

Akshay Karapurkar's user avatar

Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa

Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa

answered Mar 23, 2017 at 19:49

Michael Strobel's user avatar

A bit ‘lazy’ way to do this is to use startswith— it is easier to understand this rather regexps. However regexps might work faster, I haven’t measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

answered Oct 16, 2020 at 11:45

egvo's user avatar

egvoegvo

1,39317 silver badges24 bronze badges

Check it:

use replace()
------------
var.replace("word for replace"," ")
-----------------------------------
one = " papa is a good man"

two = " app is important"

one.replace(" papa ", " ")

output=> " is a good man"

two.replace(" app ", " ")

output=> " is important

Sallar Rabiei's user avatar

answered Apr 29, 2021 at 21:19

parth gosai's user avatar

It is better to

  1. Split the words

  2. Join the ones we are interested in with an if statement (you can pass in multiple words to strip)

    sentence = «papa is a good man»

    ‘ ‘.join(word for word in sentence.split() if word not in [‘papa’])

answered Dec 12, 2022 at 18:15

Giri's user avatar

GiriGiri

212 bronze badges

1

Table of Contents

  • Remove Word from String in Python
  • How to Remove Word from Sentence in Python
    • Using the replace() function
    • Using the re.sub() function
    • Using the startswith() function
    • Using the removeprefix() function
    • Using the endswith() function
    • Using the removesuffix() function
  • How to Remove Duplicate Words from String in Python
    • Using the set() function
    • Using the set() and join() functions
    • Using the join() and a user-defined function
    • Using the collections.OrderedDict class
    • Using the numpy.duplicate() function
    • Using the regular expressions
  • Conclusion

In this tutorial, different methods are demonstrated on how to remove word from string in Python. We will study two ways to achieve this. First, we will discuss how to remove a specific word from sentences in Python. Then, we will discuss how to remove duplicate words from a string in Python.

How to Remove Word from Sentence in Python

We will first discuss methods to remove words from a string in Python.

Using the replace() function

We can use the replace() function to remove word from string in Python. This function replaces a given substring with the mentioned substring. We can replace a word with an empty character to remove it.

For example,

a1 = «remove word from this»

a2 = a1.replace(«word», »)

print(a2)    

Output:

remove from this

We can also specify how many occurrences of a word we want to replace in the function. For this, we can use the count parameter. By default, all occurrences are replaced.

Using the re.sub() function

The regular expressions can identify parts of a string using a pattern. The re.sub() function replaces a given substring that matches the regular expression pattern with some desired string.

We can identify specific words using regular expressions and substitute them with an empty string to remove them.

See the code below.

import re

a1 = «remove word from this»

p = re.compile(‘(s*)word(s*)’)

a2 = p.sub(‘ ‘, a1)

print(a2)    

Output:

remove from this

In the above example, the re.compile() function compiles a pattern that identifies the substring word.

Using the startswith() function

This method can remove word from the start of the sentence. The startswith() function returns True or False, based on whether the string starts with a given value or not.

In this method, if the function returns True, we will slice the string till the length of the word to be removed.

See the code below.

a1 = «word remove from this»

a2 = a1[a1.startswith(‘word’) and len(‘word’):]  

print(a2)

Output:

remove from this

Using the removeprefix() function

This is similar to the previous method. It will only remove words from the start of the sentence if they exist. This function only exists in Python 3.9 and above.

For example,

a1 = «word remove from this»

a2 = a1.removeprefix(‘word’)  

print(a2)    

Output:

remove from this

Using the endswith() function

This method can remove a word from the end of a sentence. The endswith() function returns True or False, based on whether the string ends with a given value or not.

Here also, we will slice the string if the function returns True.

See the code below.

a1 = «remove from this word»

a2 = a1[:(a1.endswith(‘word’) and len(‘word’))]  

print(a2)    

Output:

remove from this

Using the removesuffix() function

This method is similar to the previous one and can eliminate a word from the end of the string. It is only available in Python 3.9 and above.

For example,

a1 = «remove from this word»

a2 = a1.removesuffix(‘word’)

print(a2)    

Output:

remove from this

How to Remove Duplicate Words from String in Python

We will now discuss how to remove duplicate words from string in Python. A common operation in these methods involves splitting a string into a list of words. For this, we use the split() function as shown in the sample codes.

Using the set() function

A set is an unordered collection of elements. It contains only unique elements. We can use it to store a collection of unique words from a string.

We can then use a for loop to compare each word and check whether it belongs in the set object or not. If the object is not present, it is appended to the final string.

We implement this logic in the code below.

a1 = «remove word from word this word»

s = set()

a2 = »

for word in a1.split():

    if word not in s:

        a2 = a2 + word + ‘ ‘

        s.add(word)

print(a2)    

Output:

remove word from this

In the above example, we can observe that we have successfully removed any duplicate words from the string a1.

Using the set() and join() functions

This method uses a similar approach to the previous method. We will proceed by splitting a string into a list of words. We will then pass this list to the set() function and automatically remove any duplicate words.

After this, we will convert the words stored in the set object back to a string. For this, we will use the join() function. With the join() function, we can combine the elements of an iterable in a string by providing the separator character for the elements.

Let us now use both these functions to remove duplicate words from a string in Python.

See the code below.

a1 = «remove word from word this word»

l = a1.split()

a2 = ‘ ‘.join(sorted(set(l), key = l.index))

print(a2)    

Output:

remove word from this

In the above example, we use the sorted() function to maintain the order of the words in the string. We sort it by their index in the list l.

Using the join() and a user-defined function

This method also follows a similar approach to the previous one. We will start by splitting the string into a list of words. In this method, instead of using the sets to remove any duplicate, we will create a function that will eliminate duplicate words from the list.

For example,

def lst_unique(l):

    lst = []

    [lst.append(x) for x in l if x not in lst]

    return lst

a1 = «remove word from word this word»

l = a1.split()

a2 = ‘ ‘.join(lst_unique(l))

print(a2)    

Output:

remove word from this

In the above example, the lst_unique() function ensures that every element of the list is unique.

Using the collections.OrderedDict class

The collections.OrderedDict class creates a dictionary by arranging the order of the elements. We store the elements as keys and combine them using the join() function.

For example,

collections.OrderedDict</code> class«>

from collections import OrderedDict

a1 = «remove word from word this word«

l = a1.split()

a2 = ‘ ‘.join(OrderedDict((s,s) for s in l).keys())

print(a2)    

Output:

remove word from this

Using the numpy.duplicate() function

The numpy.duplicate() function creates arrays from existing arrays, lists by eliminating the duplicate elements. We can use the list of words to create such an array of unique elements. After this, we will combine the elements using the join() function as done in the previous methods.

The downside of this method is that it sorts the element, so the original order of the string is lost.

See the code below.

numpy.duplicate()</code> function«>

import numpy as np

a1 = «remove word from word this word«

l = a1.split()

arr = np.unique(l)

a2 = ‘ ‘.join(arr)

print(a2)    

Output:

from remove this word

Using the regular expressions

We can use regular expressions to detect sub-strings based on regular expression patterns. We can use regular expressions to remove consecutive duplicate words using some pattern.

We will use the re.sub() function to substitute the words that will match this pattern with the first occurrence of the word.

See the code below.

import re

a1 = «remove word word word from this»

a2 = re.sub(r‘b(w+)( 1b)+’, r‘1’, a1)

print(a2)    

Output:

remove word from this

Conclusion

This article demonstrated how to remove word from String in Python. Let’s wrap up with the most straightforward methods discussed. The replace() and re.sub() function can remove a specific word from a string very easily. Other methods remove words from the start or end of the sentence. We also discussed how to remove duplicate words from a string in Python. The main approach to remove duplicate words was to split the string into an iterable, remove the duplicate items, and combine them into a string again.

You are here: Home / Python / Remove Specific Word from String in Python

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

string_with_words = "This is a string."

string_without_is = string_with_words.replace("is","")

print(string_without_is)

#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.

We can use the replace() function to remove words from a string.

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

string_with_words = "This is a string."

string_without_is = string_with_words.replace("is","")

print(string_without_is)

#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 code.

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.

If you would like to replace full words with other words, instead of remove them, we can do that too. Let’s replace the word “a” with “the”.

string_with_spaces = "This is a string."

string_with_the = string_with_spaces.replace("a","the")

print(string_with_the)

#Output:
This is the string.

Hopefully this article has been useful for you to learn how to remove words from strings in Python.

Other Articles You’ll Also Like:

  • 1.  How to Add Commas to Numbers in Python
  • 2.  Using Python to Split String into Dictionary
  • 3.  Zip Two Lists in Python
  • 4.  Python Check if List Index Exists Using Python len() Function
  • 5.  Convert String into Tuple in Python
  • 6.  Remove Element from Set in Python
  • 7.  How to Write Excel File to AWS S3 Bucket Using Python
  • 8.  Read Last N Lines of File in Python
  • 9.  Remove Decimal from Float in Python
  • 10.  Are Dictionaries Mutable in Python? Yes, Dictionaries are Mutable

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

How to Remove a Specific Character from a String in Python

When coding in Python, there may be times when you need to remove a character from a string.

Removing characters from strings is handy if you are working with user-generated inputs and need to clean your data and remove unwanted characters.

Specifically, you may need to remove only one instance of a character or even all occurrences of a character from a string.

Python offers many ways to help you do this.

Two of the most common ways to remove characters from strings in Python are:

  • using the replace() string method
  • using the translate() string method

When using either of the two methods, you can specify the character(s) you want to remove from the string.

Both methods replace a character with a value that you specify. And if you specify an empty character instead, the character you want to remove gets deleted without a replacement.

Something to note when using these methods is that the original string doesn’t get altered since strings are immutable. Instead, both methods return a new modified string that doesn’t contain the characters you wanted to remove.

In this article, you will learn how to use both methods to remove a character or multiple characters from a string with the help of coding examples.

Here is what we will cover:

  1. How to remove a specific character from a String using the replace() method
  2. How to remove multiple characters from a string using the replace() method
    1. Remove multiple characters with method chaining
    2. Remove multiple characters with a for loop
    3. Remove multiple characters with regular expressions
  3. How to remove a specific character from a string using the translate() method
  4. How to remove multiple characters from a string using the translate() method

Let’s dive in!

How to Remove a Specific Character from a String in Python Using the replace() Method

The general syntax for the replace() method looks something similar to the following:

string.replace( character, replacement, count)

Let’s break it down:

  • You append the replace() method on a string.
  • The replace() method accepts three arguments:
    • character is a required argument and represents the specific character you want to remove from string.
    • replacement is a required argument and represents the new string/character that will take the place of character.
    • count is an optional argument that represents the maximum number of character occurrences you want to remove from string. If you don’t include count, then by default, the replace() method will remove all the occurrences of character.

The replace() method doesn’t modify the original string. Instead, its return value is a copy of the original string without the characters you wanted to remove.

Now, let’s see replace() in action!

Say you have the following string, and you want to remove all of the exclamation marks:

my_string = "Hi! I! Love! Python!"

Here is how you would remove all the occurrences of the ! character:

my_string = "Hi! I! Love! Python!"

my_new_string = my_string.replace("!", "")

print(my_new_string)

# output

# Hi I Love Python

In the example above, I appended the replace() method to my_string.

I then stored the result in a new variable named my_new_string.

Remember, strings are immutable. The original string remains unchanged — replace() returns a new string and doesn’t modify the original one.

I specified that I wanted to remove the ! character and indicated that I wanted to replace ! with an empty character.

I also didn’t use the count argument, so replace() replaced all occurrences of the ! character with an empty one.

The original string stored in a variable my_string has four occurrences of the ! character.

If I wanted to remove only three occurrences of the character and not all of them, I would use the count argument and pass a value of 3 to specify the number of times I would like to replace the character:

my_string = "Hi! I! love! Python!"

my_new_string = my_string.replace("!", "", 3)

print(my_new_string)

# output

# Hi I love Python!

How to Remove Multiple Characters from A String in Python Using the replace() Method

There may be a time when you will need to replace multiple characters from a string.

In the following sections, you will see three ways you can achieve this using the replace() method.

Remove Multiple Characters With Method Chaining

One way you could achieve this is by chaining the replace() method like so:

my_string = "Hi!? I!? love!? Python!?"

my_new_string = my_string.replace("!","").replace("?","")

print(my_new_string)

# output

# Hi I love Python

That said, this way of removing characters can be quite difficult to read.

Remove Multiple Characters With A for Loop

Another way to accomplish this is to use the replace() method inside a for loop:

my_string = "Hi!? I!? love!? Python!?"

replacements = [('!', ''), ('?', '')]

for char, replacement in replacements:
    if char in my_string:
        my_string = my_string.replace(char, replacement)

print(my_string)

# output

# Hi I love Python

I first created a string that contains the two characters I want to remove, ! and ?, and stored it in the variable my_string.

I stored the characters I want to replace, along with their replacements, in a list of tuples with the name replacements — I want to replace ! with an empty string and ? with an empty string.

Then, I used a for loop to iterate over the list of tuples (if you need a refresher on for loops, give this article a read).

Inside the for loop, I used the in operator to check whether the characters are inside the string. And if they were, I used the replace() method to replace them.

Finally, I reassigned the variable.

Remove Multiple Characters With Regular Expressions

And yet another way to accomplish this is by using the regular expression library re and the sub method.

You first need to import the library:

import re

Then, specify the group of characters you want to remove (in this case, the ! and ? characters), along with the characters you want to replace them with. In this case, the replacement is an empty character:

import re

my_string = "Hi!? I!? love!? Python!?"

my_new_string = re.sub('[!?]',"",my_string)

print(my_new_string)

# output

# Hi I love Python

How to Remove a Specific Character from a String in Python Using the translate() Method

Similarly to the replace() method, translate() removes characters from a string.

With that said, the translate() method is a bit more complicated and not the most beginner-friendly.

The replace() method is the most straightforward solution to use when you need to remove characters from a string.

When using the translate() method to replace a character in a string, you need to create a character translation table, where translate() uses the contents of the table to replace the characters.

A translation table is a dictionary of key-value mappings, and each key gets replaced with a value.

You can use the ord() function to get the character’s Unicode value and then map that value to another character.

This method returns a new string where each character from the old string gets mapped to a character from the translation table.

The return value is a new string.

Let’s see an example using the same code from the previous sections:

my_string = "Hi! I! love! Python!"

my_new_string = my_string.translate( { ord("!"): None } )

print(my_new_string)

# output

# Hi I love Python

In the example above, I used the ord() function to return the Unicode value associated with the character I wanted to replace, which in this case was !.

Then, I mapped that Unicode value to None — another word for nothing or empty — which makes sure to remove it. Specifically, it replaced every instance of the ! character with a None value.

How to Remove Multiple Characters from a String in Python Using the translate() Method

What if you need to replace more than one character using the translate() method? For that, you can use an iterator like so:

my_string = "Hi!? I!? love!? Python!?"

my_new_string = my_string.translate( { ord(i): None for i in '!?'} )

print(my_new_string)

# output

# Hi I love Python

In the example above, I replaced both ! and ? characters with the value None by using an iterator that looped through the characters I wanted to remove.

The translate() method checks whether each character in my_string is equal to an exclamation point or a question mark. If it is, then it gets replaced with None.

Conclusion

Hopefully, this article helped you understand how to remove characters from a string in Python using the built-in replace() and translate() string methods.

Thank you for reading, and happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

In this python tutorial, we will discuss Python remove substring from a string and also cover the below points:

  • Remove substring from string python regex
  • Remove substring from string python DataFrame
  • Python remove substring from string by index
  • Remove duplicate substring from string python
  • Remove the last substring from string python
  • Remove multiple substrings from string python
  • Remove the first substring from string python
  • Remove substring from beginning of string python
  • Python remove substring from a string if exists
  • Remove a substring from a string python pandas
  • How to remove all occurrences of a substring from a string in python
  • Python remove substring from the middle of a string

A substring is a contiguous sequence of characters. We extract these substrings using the substring method.

  • When you give the substring method one number the result in the section from that position to the end of the string.
  • If you have two numbers, you get the section starting at the start index up to but not including the end position.
  • For example, abcdef is a string where the cd is a substring of this string.

Syntax:

Here is the syntax of Substring

Str.substring(start)

Str.substring(start,end)

Python remove substring from a String

  • In this section, we will learn how to remove substring from a string.
  • Python removes a character from a string offers multiple methods by which we can easily remove substring from a string.
    • String replace()

String replace() method replaces a specified character with another specified character.

Syntax:

Here is the Syntax of String replace()

replace[
         old_Str1,
         new_Str2,
         instance
        ]

Let’s take an example to check how to remove substring from a string in Python.

str2="calfornia"
str3= str2.replace("a","")
print(str3)

Here is the screenshot of following given code.

Python remove substring from a string
Python remove substring from a string

This is how to remove substring from a String in Python.

Read: Python 3 string replace() method example

Remove substring from string python regex

  • In this section, we will learn how to remove substring from string python regex.
  • Regular Expression is basically used for describing a search pattern so you can use regular expression for searching a specific string in a large amount of data.
  • You can verify that string has a proper format or not you can find a string and replace it with another string and you can even format the data into a proper form for importing so these are all uses of the regular expression.
  • Now over here I have shown you an example here.
  • There is a string that is present in which they have written George is 22 and Michael is 34. So as you can see what are useful data that I can find here only name and age.
  • So what I can do I can identify a pattern with the help of regular expression.
  • I can convert that to a dictionary.

Let’s take an example to check how to remove substring from string python regex.

import re
from typing import Pattern
new_str1 = "George"
pattern = r'[oe]'
mod1_str2 = re.sub(pattern, '', new_str1)
print(mod1_str2)

Here is the screenshot of following given code.

Remove substring from string python regex
Remove substring from string python regex

This is how to remove substring from string using regex in Python (python remove substring from string regex).

Read: Python compare strings

Remove substring from string python DataFrame

DataFrame is two dimensional and the size of the data frame is mutable potentially heterogeneous data. We can call it heterogeneous tabular data so the data structure which is a dataframe also contains a labeled axis which is rows and columns and arithmetic operation aligned on both rows and column tables. It can be thought of as a dictionary-like container.

  • In this section, we will learn how to remove substring from string Python DataFrame.
  • First, we have to create a DataFrame with one column that contains a string.
  • Then we have to use a string replace() method to remove substring from a string in Python DataFrame.

Let’s take an example to check how to remove substring from string python DataFrame.

import pandas as pd

dt = {'ALPHABET':  ['a','z','f','h']
          
         }
df = pd.DataFrame(dt, columns= ['ALPHABET'])
df['ALPHABET'] = df['ALPHABET'].str.replace('a','')
print (df)

Here is the screenshot of following given code.

Remove substring from string python dataframe
Remove substring from string python dataframe

This is how to remove substring from string in Python DataFrame.

Read: Crosstab in Python Pandas

Python remove substring from string by index

Index String method is similar to the fine string method but the only difference is instead of getting a negative one with doesn’t find your argument.

  • In this section, we will learn how to remove substring from string by index.b-1.
  • Remove substring from a string by index we can easily use string by slicing method.
  • String Slicing returns the characters falling between indices a and b.Starting at a,a+1,a+2..till b-1.

Syntax:

Here is the syntax of string slicing.

String
      [start:end:step_value]

Let’s take an example to check how to remove substring from string by index.

str1 = 'George'
str3 = str1[:2] + str1[3:]
print(str3)

Here is the screenshot of following given code.

Remove substring from string python by index
Remove substring from string python by index

This is how to remove substring from string by index in Python.

Read: Python 3 string methods with examples

Remove duplicate substring from string Python

Let’s take an example this is a given string ‘abacd’. Now you can see that ‘a’ is repeating two times and no other character is repeating. So after removing all the duplicates. The result will be a b c d’. The condition is that you need to remove all the duplicates provided the order should be maintained.

  • In this section, we will learn how to remove duplicate substring from string python.
  • Using set() +split() method to remove Duplicate substring.

Syntax:

Here is the Syntax of set() +split()

set[
    (sub.split(''))
    ]

Let’s take an example to check how to remove duplicate substring from string python.

str1 = ['u-u-k','mm-cc','bb-cc']
print("original string :" + str(str1))
result = [set(sub.split('-')) for sub in str1]
print(" string after duplicate removal :" + str(result))

Here is the screenshot of following given code.

Remove dupicate substring from string python
Remove dupicate substring from string python

The above Python code to remove duplicate substring from string in Python.

Read: Python NumPy arange

Remove last substring from string python

  • In this section, we will learn how to remove the last substring from string Python.
  • Using the Naive method On the off chance that the first letter of the provided substring matches, we start an inner loop to check if all components from the substring match with the successive components in the main string. That is, we just check whether the whole substring is available or not.

Let’s take an example to check how to remove the last substring from string Python.

str1 = 'Micheal'
str2 = 'eal'
print ("First_strings : ", str1, "nsubstring : ", str2) 
if str1.endswith(str2):
    result = str1[:-(len(str2))]
print ("Resultant string", result)

Here is the screenshot of following given code.

Remove last substring from string python
python remove substring from string end

This is how to remove last substring from string in Python.

Read: Could not convert string to float Python

Remove first substring from string python

  • In this section, we will learn how to remove the first substring from string python.
  • Remove the first substring from the string we can easily use string by slicing method.
  • String Slicing returns the characters falling between indices a and b.Starting at a,a+1,a+2..till b-1.

Syntax:

Here is the syntax of String Slicing.

String
      [start:end:step_value]

Let’s take an example to check how to remove the first substring from string python

str1 = "smith"
str2 = str1[2:]
print(str2)

Here is the screenshot of following given code.

Remove first substring from string in python
python remove substring from string start

The above Python code we can use to remove first substring from string in Python.

Read: Python NumPy append

Remove substring from beginning of string python

  • In this section, we will learn how to remove substring from the beginning of string python.
  • Using loop + remove() + startswith() remove substring from beginning of string.

Syntax:

Here is the syntax of loop + remove () +startswith()

for str in str1 [:]:
 if str.startswith[pref]:

Let’s take an example to check how to remove substring from beginning of string python.

str2="calfornia"
str3= str2.replace("c","")
print(str3)

Here is the screenshot of following given code.

Remove substring from beginning of string python
Remove substring from beginning of string python

Read: Python find substring in string + Examples

Python remove substring from a string if exists

  • In this section, we will learn how to remove a substring from a string if exists.
  • String replace() method remove substring from a string if exists.

Syntax:

Here is the syntax of string replace

replace[
         old_Str1,
         new_Str2,
         instance
        ]

Let’s take an example to check how to remove substring from a string if exists

str2="calfornia"
str3= str2.replace("a","")
print(str3)

Here is the screenshot of following given code.

Python remove substring from a string if exists
Python remove substring from a string if exists

This is how to remove substring from a string if exists in Python.

Remove a substring from a string python pandas

Pandas is a python library that is used for data manipulation analysis and cleaning. Python pandas are well-suited for different kinds of data such as we can work on tabular data.

  • In this section, we will learn how to remove a substring from a String Python pandas.
  • First, we have to create a Data Frame with one Column that contains a String.
  • Then we have to use a string replace() method which specified character with another specified character.

String replace() method remove a substring from a string python pandas.

Syntax:

Here is the syntax of String replace()

Column name
           [
            replace[
        
        old_Str1,
        new_Str2,
        instance
       ]
]

Let’s take an example to check how to remove a substring from a string Python Pandas

import pandas as pd

dt = {'ALPHABET':  ['a','z','f','h']
          
         }
df = pd.DataFrame(dt, columns= ['ALPHABET'])
df['ALPHABET'] = df['ALPHABET'].str.replace('a','l')
print (df)

Here is the screenshot of following given code.

Remove a substring from a string python pandas
Remove a substring from a string python pandas

The above Python code, we can use to remove a substring from a string in python pandas.

Read: Could not convert string to float Python

How to remove all occurrences of a substring from a string in python

  • In this section, we will learn how to remove all occurrences of a substring from a string in python.
  • String translate() will change the string by replacing the character or by deleting the character. We have to mention the Unicode for the character and None as a replacement to delete it from the String.
  • Use the String translate() method to remove all occurrences of a substring from a string in python.

Let’s take an example to check how to remove all occurrences of a substring from a string in python.

str1 = "Micheal"
print("Original string : " + str1)
# Using translate()
temp = str.maketrans("iche", "abcd")
str1 = str1.translate(temp)
print(" string after swap : " + str(str1)) 

Here is the screenshot of following given code.

Remove all occurences of a substring from a string in python
Remove all occurences of a substring from a string in python

The above Python code, we can use to remove all occurrences of a substring from a string in python.

Python remove substring from the middle of a string

  • In this section, we will learn how to remove substring from the middle of a string.
  • The string replace() method remove the substring from the middle of a string.

Syntax:

Here is the syntax of String replace

replace[
         old_Str1,
         new_Str2,
         instance
        ]

Let’s take an example to check how to remove substring from the middle of a string.

str1 = input("Enter the string").replace("the","")
print(str1)

Here is the screenshot of following given code

Remove substring from the middle of a string
Remove substring from the middle of a string

The above Python code, we can use to remove substring from the middle of a string in Python.

You may like the following Python tutorials:

  • Slicing string in Python + Examples
  • Convert string to float in Python
  • Append to a string Python + Examples

In this python tutorial we learned about how to remove substring from a String in Python with the below examples:

  • How to remove substring from a String in Python
  • Remove substring from string python regex
  • How to remove substring from string python DataFrame
  • Python remove substring from string by index
  • How to remove duplicate substring from string Python
  • Remove last substring from string python/
  • How to remove first substring from string python
  • Remove substring from beginning of string python
  • Python remove substring from a string if exists
  • Remove a substring from a string python pandas
  • How to remove all occurrences of a substring from a string in python
  • Python remove substring from the middle of a string

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Понравилась статья? Поделить с друзьями:
  • How to remove row in excel
  • How to remove password excel
  • How to make word problems
  • How to make word games
  • How to make word document