close

How to remove specific substrings from a set of strings in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to remove specific substrings from a set of strings in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to remove specific substrings from a set of strings in Python?

  1. How to remove specific substrings from a set of strings in Python?

    This means you have to re-allocate the set or re-populate it (re-allocating is easier with a set comprehension):

  2. remove specific substrings from a set of strings in Python

    This means you have to re-allocate the set or re-populate it (re-allocating is easier with a set comprehension):

Method 1

Strings are immutable. str.replace creates a new string. This is stated in the documentation:

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. […]

This means you have to re-allocate the set or re-populate it (re-allocating is easier with a set comprehension):

new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}

Method 2

>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'

.replace doesn’t change the string, it returns a copy of the string with the replacement. You can’t change the string directly because strings are immutable.

You need to take the return values from x.replace and put them in a new set.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read