How to replace all occurrences of a string

0 votes

I have this string:

"Test abc test test abc test test test abc test test abc"

Doing:

str = str.replace('abc', '');

seems to only remove the first occurrence of abc in the string above.

How can I replace all occurrences of it?

Nov 26, 2020 in Python by anonymous
• 65,890 points
799 views

1 answer to this question.

0 votes

The general pattern is

str.split(search).join(replacement)

This used to be faster in some cases than using replaceAll and a regular expression, but that doesn't seem to be the case anymore in modern browsers.

Conclusion: If you have a performance-critical use case (e.g processing hundreds of strings), use the Regexp method. But for most typical use cases, this is well worth not having to worry about special characters.

answered Nov 26, 2020 by Gitika
• 65,890 points

Related Questions In Python

+1 vote
2 answers

How to print first character of each word in upper case of a string in Python

class Solution:     def firstAlphabet(self, s):             self.s=s              k=''              k=k+s[0]              for i in range(len(s)):                     if ...READ MORE

answered Oct 28, 2020 in Python by Anurag
12,286 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,460 points
1,327 views
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29, 2019 in Python by rajesh
• 1,270 points
1,983 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,359 views
0 votes
1 answer
0 votes
1 answer

How to match all occurrences of a regex?

Using scan should do the trick: string.scan(/regex/) READ MORE

answered Nov 25, 2020 in Python by Gitika
• 65,890 points
2,905 views
0 votes
1 answer

How to find all occurrences of a substring?

There is no simple built-in string function ...READ MORE

answered Nov 25, 2020 in Python by Gitika
• 65,890 points
892 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP