As in 2.x, use str.replace().

Example:

>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
Answer from Ignacio Vazquez-Abrams on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_replace.asp
Python String replace() Method
HTML Reference CSS Reference JavaScript Reference SQL Reference Python Reference W3.CSS Reference Bootstrap Reference PHP Reference HTML Colors Java Reference AngularJS Reference jQuery Reference ยท HTML Examples CSS Examples JavaScript Examples How To Examples SQL Examples Python Examples W3.CSS Examples Bootstrap Examples PHP Examples Java Examples XML Examples jQuery Examples
Discussions

How to replace *all* occurrences of a string in Python, and why `str.replace` misses consecutive overlapping matches? - Stack Overflow
I want to replace all patterns 0 in a string by 00 in Python. For example, turning: '28 5A 31 34 0 0 0 F0' into '28 5A 31 34 00 00 00 F0'. I tried with str.replace(), but for some reason it misses ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnprogramming
12
6
October 18, 2023
How can I replace all \n characters in a dictionary?
Use "\n" instead of "\\n" More on reddit.com
๐ŸŒ r/learnpython
8
1
July 1, 2021
I am trying to replace all \n from my string with a new line
The call s.replaceAll(โ€œ\nโ€, โ€œโ€) replaces all new line characters (represented in Java by \n I think you want the call s.replaceAll(โ€œ\\nโ€, โ€œ\nโ€) More on reddit.com
๐ŸŒ r/javahelp
6
0
June 8, 2022
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-replace-all-occurrences-of-a-substring-in-a-string
Python - Replace all Occurrences of a Substring in a String - GeeksforGeeks
October 31, 2025 - This method builds a new string by checking each slice for the target substring. It is least efficient but works without built-in functions. ... s = "python java python html python" target = "python" replacement = "c++" res = "" i = 0 while i < len(s): if s[i:i+len(target)] == target: res += replacement i += len(target) else: res += s[i] i += 1 print(res)...
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python regex replace all
Python regex replace all - Spark By {Examples}
May 31, 2024 - In Python, you can use the regex re module to perform regular expression operations like replace all occurrences of strings. The re.sub() function is
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ replace
Python String replace()
Note: If count is not specified, the replace() method replaces all occurrences of the old substring with the new string.
๐ŸŒ
Real Python
realpython.com โ€บ replace-string-python
How to Replace a String in Python โ€“ Real Python
January 15, 2025 - In this tutorial, you'll learn how to remove or replace a string or substring. You'll go from the basic string method .replace() all the way up to a multi-layer regex pattern using the sub() function from Python's re module.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ string_replace.htm
Python String replace() Method
Following is the syntax for Python String replace() method โˆ’ ... This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Find elsewhere
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ replaceall-python
Mastering `replaceall` in Python: A Comprehensive Guide - CodeRivers
February 22, 2026 - If not specified, all occurrences of old will be replaced. ... original_string = "Hello, world! Hello, Python!" new_string = original_string.replace("Hello", "Hi") print(new_string) In this example, all occurrences of the substring "Hello" in the original_string are replaced with "Hi".
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-string-replace
Python String replace() Method - GeeksforGeeks
1 week ago - Return Value: A new string with the specified replacements applied. The original string is not modified because strings in Python are immutable. Example 1: Here, only the first occurrence of a substring is replaced using the count parameter.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ string-replace-method
Master Python's String Replace Method for Text Manipulation
Explore Python's string replace() method to update text seamlessly. Learn to replace substrings, fix user input, and process files with practical examples.
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ python-string-replaceall
Python String ReplaceAll: A Comprehensive Guide - CodeRivers
April 17, 2025 - In Python programming, strings are an essential data type used to represent text. Manipulating strings is a common task, and one of the most useful operations is replacing all occurrences of a specific substring within a string. While Python doesn't have a built-in `replaceall` method exactly as some other languages do, it provides the `replace` method which can achieve a similar effect.
๐ŸŒ
pytz
pythonhosted.org โ€บ replaceall โ€บ README.html
replaceall โ€” replaceall 0.1 documentation
replaceall is a Python 2.7/3 module to replace or remove one or more Chars from a given string.
๐ŸŒ
Medium
medium.com โ€บ @tajammalmaqbool11 โ€บ python-string-replace-the-complete-guide-with-examples-dc81506ae084
Python String Replace: The Complete Guide with Examples | by Tajammal Maqbool | Medium
October 10, 2025 - In this guide, weโ€™ll explore how to use Python string replace, along with practical examples, best practices, and performance tips.
๐ŸŒ
Interview Kickstart
interviewkickstart.com โ€บ home โ€บ blogs โ€บ learn โ€บ python string replace() method
Python String Replace() Method | Interview Kickstart
September 25, 2024 - Thor was a god of war and lightning. Thor was physically strong.โ€ print(input_string.replace(โ€œThorโ€,โ€Lokiโ€,2)) In this example, we use the count parameter. The input string contains three occurrences of โ€œThor.โ€ We only want to ...
Address ย  4701 Patrick Henry Dr Bldg 25, 95054, Santa Clara
(4.7)
๐ŸŒ
Python Basics
pythonbasics.org โ€บ home โ€บ python basics โ€บ python string replace() method
Python String replace() Method - pythonbasics. ...
Python has builtin support for string replacement. A string is a variable that contains text data. If you don't know about strings, you can read more about stri
Top answer
1 of 1
7

A better tactic would be to not look for spaces around the individual zeros, but to use regex substitution and look for word boundaries (\b):

>>> import re
>>> re.sub(r'\b0\b', '00', '28 5A 31 34 0 0 0 F0')
'28 5A 31 34 00 00 00 F0'

This has the added benefit that a 0 at the start or end of the string would get replaced into 00 as well.

If you want the exact same semantics, you could use positive lookbehind and lookahead to not "consume" the space characters:

>>> re.sub(r'(?<= )0(?= )', '00', '28 5A 31 34 0 0 0 F0')
'28 5A 31 34 00 00 00 F0'

The reason why your original attempt does not work is that when str.replace (or re.sub) finds a pattern to be replaced, it moves forward to the next character following the whole match.

So:

'28 5A 31 34 0 0 0 F0'.replace(' 0 ', ' 00 ')
#           ^-^      #1 match, ' 0 ' โ†’ ' 00 '
#              ^     start looking for second match from here
#               ^-^  #2 match, ' 0 ' โ†’ ' 00 '
'28 5A 31 34 00 0 00 F0'
#           ^--^ ^--^
#            #1   #2

The CPython (3.13.3) str.replace implementation can be seen from here: https://github.com/python/cpython/blob/6280bb547840b609feedb78887c6491af75548e8/Objects/unicodeobject.c#L10333, but it's a bit complex with all the Unicode handling.


If it would work as you'd "wish", you still wouldn't get the output that you desire, as you'd get extra spaces (each overlapping  0  in the original string would cause its own  00  to appear into the output string):

# Hypothetical:
'28 5A 31 34 0 0 0 F0'.replace(' 0 ', ' 00 ')
#           ^-^      #1 match, ' 0 ' โ†’ ' 00 '
#             ^-^    #2 match, ' 0 ' โ†’ ' 00 '
#               ^-^  #3 match, ' 0 ' โ†’ ' 00 '
'28 5A 31 34 00  00  00 F0'
#           ^--^^--^^--^
#            #1  #2  #3

If it still seems unintuitive why you'd get those extra spaces, consider ABA to be  0  and X__X to be  00 , and look at this:

# Analogous to: ' 0 0 0 '.replace(' 0 ', ' 00 ')
'ABABABA'.replace('ABA', 'X__X')
'X__XBX__X'     # What you get in reality now.
'X__XX__XX__X'  # What you would get with the above logic (=extra consecutive X characters, i.e. spaces).

And finally, if it would work like calling replace as many times as there's something to replace does, a trivial 'A'.replace('A', 'AA') would just loop infinitely ('A'โ†’'AA'โ†’'AAAA'โ†’โ€ฆ).


So, it just "has" to work this way. This is exactly why regex allows using lookahead and lookbehind to control which matched parts actually consume characters from the original string and which don't.

๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ python โ€บ strings โ€บ .replace()
Python | Strings | .replace() | Codecademy
June 18, 2025 - This example uses the .replace() method with the count parameter to replace only the first occurrence (count = 1) of โ€œlikeโ€ with โ€œloveโ€ in the var string: ... I love cats and cats like me.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-replace-all-occurrences-of-a-character-in-a-string-in-Python
How to replace all occurrences of a character in a string in Python - Quora
Answer (1 of 3): Letโ€™s assume you need to replace all โ€˜Xโ€™ characters in a 10 character string with โ€˜Yโ€™. You can do this by replacing all characters with โ€˜Yโ€™. For example: 1. You start with the ten character string: โ€œBoX of BoXesโ€. 2. You iterate through the string replacing ...
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ python string methods โ€บ python string replace()
How to Use Python String replace() to Replace a Substring in a String
December 28, 2020 - Python will, Python will rock you! The following example uses the replace() method to replace the first occurrence of the substring 'bye' by the new substring 'baby': s = 'Baby bye bye bye!' new_s = s.replace('bye', 'baby', 1) print(new_s)Code language: PHP (php) ... Baby baby bye bye!