The problem is that you are not doing anything with the result of replace. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.

line[8] = line[8].replace(letter, "")
Answer from Matti Virkkunen on Stack Overflow
๐ŸŒ
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
August 13, 2026 - Explanation: re.sub(pattern, replacement, string) finds all occurrences of pattern and replaces them with replacement. This method splits the string at each occurrence of the target and joins it back with the replacement.
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
How to replace a string that is all the same character at a specific index?
Slice and concatenate. string1 = string1[:-1] + 'b' More on reddit.com
๐ŸŒ r/learnpython
10
10
May 4, 2024
How to find all occurrences of a substring in a string while ignore some characters in Python?
You could use re for this. ex import re long_string = 'this is a t`es"t. Does the test work?' small_string = "test" chars_to_ignore = ['"', '`'] print(re.findall(f"[{''.join(chars_to_ignore)}]*".join(small_string), long_string)) More on reddit.com
๐ŸŒ r/learnpython
6
1
July 25, 2024
How to change all occurrences of selected text in a file?
ctrl + h https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf More on reddit.com
๐ŸŒ r/vscode
7
24
February 6, 2021
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse ... ... The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified...
๐ŸŒ
Real Python
realpython.com โ€บ replace-string-python
How to Replace a String in Python โ€“ Real Python
October 22, 2025 - To replace all occurrences of a substring in a string, use the .replace() method with the substring you want to replace and the new string as arguments. This method replaces all instances of the substring in the original string.
๐ŸŒ
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 ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-replace-all-occurrences-of-a-string-with-another-string-in-Python
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. The following example shows the usage of Python String replace() method...
Find elsewhere
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ replace-occurrences-of-a-substring-in-string-with-python
Replace Occurrences of a Substring in String with Python
September 21, 2020 - Python offers easy and simple functions for string handling. The easiest way to replace all occurrences of a given substring in a string is to use the replace() function.
๐ŸŒ
All About AI-ML
indhumathychelliah.com โ€บ 2020 โ€บ 12 โ€บ 20 โ€บ different-ways-to-replace-occurences-of-a-substring-in-python-strings
Different Ways to Replace Occurences of a Substring in Python Strings โ€“ All About AI-ML
January 2, 2022 - By using the above-mentioned methods, letโ€™s see how to replace substrings in strings. ... s1="one apple,two orange,two banana" s2=s1.replace("two","one") print (s2) #Output:one apple,one orange,one banana ยท By default, str.replace() will replace all occurrences of โ€œtwoโ€ by โ€œoneโ€
๐ŸŒ
YouTube
youtube.com โ€บ watch
Replace All Occurrences Of A String In A File | Python Example - YouTube
How to replace all occurrences of a string in a file with another string using Python. Source code: https://github.com/portfoliocourses/python-example-code/...
Published: October 14, 2023
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-string-replace
Python String Replace Methods | Using replace() and More
August 19, 2024 - If you want to replace all occurrences, you simply skip this parameter. text = 'apple apple apple' new_text = text.replace('apple', 'orange') print(new_text) # Output: 'orange orange orange' In this example, all instances of โ€˜appleโ€™ are ...
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.

๐ŸŒ
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
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-string-replace
Python String replace() Method - GeeksforGeeks
October 28, 2024 - Explanation: Here, "Hello" is replaced by "Hi" throughout the string, resulting in "Hi World! Hi Python!". Note: Since replace() creates a new string, the original string remains unchanged. ... count (optional): Specifies the maximum number of replacements to perform. If omitted, all occurrences are replaced.
๐ŸŒ
TechBeamers
techbeamers.com โ€บ replace-occurrences-string-python
Simple Ways to Replace Occurrences of a Char in Python
November 30, 2025 - You should note the following points while using the string.replace() method: If the count parameter is not specified, all occurrences of the old string will be replaced with the new one.
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ replace-all-occurrences-of-a-string-in-a-pandas-dataframe.aspx
Python - Replace all occurrences of a string in a pandas dataframe
September 26, 2023 - # Importing pandas package import pandas as pd # Creating a dictionary d = { 'a': ['1*', '2*', '3'], 'b': ['4*', '5*', '6*'] } # Creating a DataFrame df = pd.DataFrame(d) # Display original DataFrame print("Original DataFrame :\n",df,"\n") # Replacing all occurrences of * in DataFrame for col in df.columns: df[col] = df[col].str.replace('*', '#') # display modified DataFrame print("Result:\n",df)
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ replace
Python String replace()
Online Python Online JavaScript ... Online Go Online Rust Online Scala Online Dart Online R Online Ruby ... The replace() method replaces each matching occurrence of a substring with another string....
๐ŸŒ
THECODE11
thecode11.com โ€บ home โ€บ python โ€บ how to replace all occurrences of a string in python
How to replace all occurrences of a string in Python
January 5, 2026 - However, be readable with your code. text = "abc" result = text.replace("a", "1").replace("b", "2").replace("c", "3") print(result) # Output: 123 ยท For 90% of use cases, Python's built-in replace() method is sufficient, readable, and fast.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-string-replace-function-in-python-for-substring-substitution
Python String.Replace() โ€“ Function in Python for Substring Substitution
January 24, 2022 - When using the .replace() Python method, you are able to replace every instance of one specific character with a new one. You can even replace a whole string of text with a new line of text that you specify. The .replace() method returns a copy of a string...