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,930 points
77 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,930 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
7,963 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,440 points
453 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,230 points
527 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 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,250 views
0 votes
0 answers
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 24, 2020 in Python by Gitika
• 65,930 points
1,325 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 24, 2020 in Python by Gitika
• 65,930 points
78 views