Python delete word from string

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

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.

In this tutorial, we will look at how to remove the first word from a string in Python with the help of some examples.

remove first word from string in python

You can use the string split() function to remove the first word from a string. The split() function is generally used to split a string into its constituent words based on a delimiter, which, by default, is a whitespace character. For example –

# create a string
s = "You are a wizard Harry!"
# split the string
print(s.split())

Output:

['You', 'are', 'a', 'wizard', 'Harry!']

You can see that using the string split() function on the above string resulted in a list of words. You can now slice this list of words to remove the first word and reconstruct a sentence from the remaining words using the string join() function.

# create a string
s = "You are a wizard Harry!"
# split the string
words = s.split()
# remove first word and join the remaning words
print(" ".join(words[1:]))

Output:

are a wizard Harry!

The resulting string does not have the first word from the original string.

You can also accomplish the above task using just the string split() function. For this, pass an additional parameter, maxsplit = 1 to the split() function. This parameter indicates the number of splits to make.

# create a string
s = "You are a wizard Harry!"
# split the string
print(s.split(maxsplit=1))

Output:

['You', 'are a wizard Harry!']

You can see that it results in a list of just two strings from splitting the original string just once (this split is done on the first occurrence of the delimiter, a whitespace character in our case).

Now, we can take the value at index 1 from the above list to get our resulting string with the first word removed. Here’s the complete code –

# create a string
s = "You are a wizard Harry!"
# remove the first word
print(s.split(maxsplit=1)[1])

Output:

are a wizard Harry!

The first word is removed.

For more on the string split() function, refer to its documentation.

Using slicing to remove the first word

Alternatively, you can use the slice operation to remove the first word from the string.

For this, we slice the string from the length of the first word to the end of the string and then apply the string lstrip() function to remove any whitespaces in the string start after the slice operation.

# create a string
s = "You are a wizard Harry!"
# remove the first word
print(s[3:].lstrip())

Output:

are a wizard Harry!

We get the same result as above.

For this method to work, you need to know the length of the first word in advance. If that is not the case, you might have to use the string split() function. Thus, it is recommended that you use the string split() method.

You might also be interested in –

  • Python – Remove First N Characters From String
  • Remove First Character From String in Python

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

While handling text data in python, we sometimes need to remove a specific substring from the text. In this article, we will discuss different ways to remove a substring from a string in Python.

Table of Contents

  1. Remove Substring From String in Python Using split() Method
  2. Remove Substring From String in Python Using Using the join() Method
  3. Remove Substring From String in Python Using the replace() Method 
  4. Remove Substring From String in PythonUsing Regular Expressions
    1. Remove Substring From String in Python Using re.split() Method 
    2. Remove Substring From String in Python Using re.sub() Method 
  5. Remove Substring From String in Python by Index
  6. Conclusion

Remove Substring From String in Python Using split() Method

The split() method in Python is used to split a string into substrings at a separator. The split() method, when invoked on a string, takes a string in the form of a separator as its input argument. After execution, it returns a list of substrings from the original string, which is split at the separator. 

To remove a substring from a string in Python using the split() method, we will use the following steps.

  • First, we will create an empty string named output_string to store the output string.
  • Then, we will use the split() method to split the string into substrings from the positions where we need to remove a specific substring. For this, we will invoke the split() method on the input string with the substring that needs to be removed as the input argument. After execution, the split() method will return a string of substrings. We will assign the list to a variable str_list.
  • Once we get the list of strings, we will iterate through the substrings in str_list using a for loop. During iteration, we will add the current substring to output_string using the string concatenation operation. 

After execution of the for loop, we will get the required output string in the variable output_string. You can observe this in the following code.

myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = ""
str_list = myStr.split(substring)
for element in str_list:
    output_string += element

print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)

Output:

The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free  tutorials for you to learn .

In the output, you can observe that the substring python has been removed from the input string.

Remove Substring From String in Python Using Using the join() Method

Performing string concatenation several times requires unnecessary storage and time. Therefore, we can avoid that by using the join() method. 

The join() method, when invoked on a separator string, takes an iterable object as its input argument. After execution, it returns a string consisting of the elements of the iterable object separated by the separator string.

To remove substring from a string in python using the join() method, we will use the following steps.

  • First,  we will use the split() method to split the input string into substrings from the positions where we need to remove a specific substring. For this, we will invoke the split() method on the input string with the substring that needs to be removed as the input argument. After execution, the split() method will return a string of substrings. We will assign the list to a variable str_list.
  • Next, we will invoke the join() method on an empty string with str_list as its input argument. 

After execution of the join() method, we will get the required string output as shown below.

myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
str_list = myStr.split(substring)
output_string = "".join(str_list)
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)

Output:

The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free  tutorials for you to learn .

Here, you can observe that we have converted the list returned by the split() method into a string using the join() method. Thus, we have avoided repeated string concatenation as we did in the previous example.

Remove Substring From String in Python Using the replace() Method 

The replace() method is used to replace one or more characters from a string in python. When invoked on a string, the replace() method takes two substrings as its input argument. After execution, it replaces the substring in the first argument with that of the second input argument. Then it returns the modified string. 

To remove a substring from a string using the replace() method, we will invoke the replace() method on the original string with the substring that is to be removed as the first input argument and an empty string as the second input argument. 

After execution of the replace() method, we will get the output string as shown in the following example.

myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = myStr.replace(substring, "")
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)

Output:

The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free  tutorials for you to learn .

Here, we have removed the required substring from the input string in a single statement using the replace() method.

Remove Substring From String in PythonUsing Regular Expressions

Regular expressions provide us with efficient ways to manipulate strings in Python. We can also use regular expressions to remove a substring from a string in python. For this, we can use the re.split() method and the re.sub() method.

Remove Substring From String in Python Using re.split() Method 

The re.split() method is used to split a text at a specified separator. The re.split() method takes a separator string as its first input argument and the text string as its second input argument. After execution, it returns a list of strings from the original string that are separated by the separator.

To remove a substring from a string in Python using the re.split() method, we will use the following steps.

  • First, we will create an empty string named output_string to store the output string.
  • Then, we will use the re.split() method to split the string into substrings from the positions where we need to remove a specific substring. For this, we will execute the re.split() method with the substring that needs to be removed as its first input argument and the text string as its second input argument. After execution, the re.split() method will return a string of substrings. We will assign the list to a variable str_list.
  • Once we get the list of strings, we will iterate through the substrings in str_list using a for loop. During iteration, we will add the current substring to output_string using the string concatenation operation. 

After execution of the for loop, we will get the required output string in the variable output_string. You can observe this in the following code.

import re

myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = ""
str_list = re.split(substring, myStr)
for element in str_list:
    output_string += element

print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)

Output:

The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free  tutorials for you to learn .

You can observe that the approach using the re.split() method is almost similar to the approach using the string split() method. However, both approaches have different execution speeds. If the input string is very large, the re.split() method should be the preferred choice to split the input string.

Performing string concatenation several times requires unnecessary memory and time. Therefore, we can avoid that by using the join() method. 

To remove substring from a string in python using the join() method, we will use the following steps.

  • First,  we will use the re.split() method to split the input string into substrings from the positions where we need to remove a specific substring.For this, we will execute the re.split() method with the substring that has to be removed as its first input argument and the text string as its second input argument. After execution, the re.split() method will return a string of substrings. We will assign the list to a variable str_list.
  • Next, we will invoke the join() method on an empty string with str_list as its input argument. 

After execution of the join() method, we will get the required string output as shown below.

import re

myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
str_list = re.split(substring, myStr)
output_string = "".join(str_list)
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)

Output:

The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free  tutorials for you to learn .

In this approach, we have obtained the output string in only two python statements. Also, we haven’t done repetitive string concatenation which takes unnecessary time.

Remove Substring From String in Python Using re.sub() Method 

The re.sub() method is used to substitute one or more characters from a string in python. The re.sub() method takes three input arguments. The first input argument is the substring that needs to be substituted. The second input argument is the substitute substring. The original string is passed as the third input string. 

After execution, the re.sub() method replaces the substring in the first argument with that of the second input argument. Then it returns the modified string. 

To remove a substring from a string using the re.sub() method, we will execute the re.sub() method with the substring that is to be removed as the first input argument, an empty string as the second input argument, and the original string as the third input argument. 

After execution of the re.sub() method, we will get the output string as shown in the following example.

import re

myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = re.sub(substring, "", myStr)
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)

Output:

The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free  tutorials for you to learn .

The re.sub() method works in a similar manner to the replace() method. However, it is faster than the latter and should be the preferred choice.

Sometimes, we might need to remove a substring from a string when we know its position in the string. To remove a substring from a string in python by index, we will use string slicing.

If we have to remove the substring from index i to j, we will make two slices of the string. The first slice will be from index 0 to i-1 and the second slice will be from index j+1 to the last character. 

After obtaining the slices, we will concatenate the slices to obtain the output string as shown in the following example.

import re

myStr = "I am PFB. I provide free python tutorials for you to learn python."
output_string = myStr[0:5]+myStr[11:]
print("The input string is:", myStr)
print("The output string is:", output_string)

Output:

The input string is: I am PFB. I provide free python tutorials for you to learn python.
The output string is: I am  provide free python tutorials for you to learn python.

Conclusion

In this article, we have discussed different ways to remove a substring from a string in Python. Out of all the approaches, the approaches using re.sub() method and the replace() method have the best time complexity. Therefore, I would suggest you use these approaches in your program.

I hope you enjoyed reading this article. To learn more about python programming, you can read this article on how to remove all occurrences of a character in a list in Python. You might also like this article on how to check if a python string contains a number.

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Понравилась статья? Поделить с друзьями:
  • Python open file with excel
  • Python datetime from excel
  • Python dataframe from excel
  • Python csv for excel
  • Python create table in word