-2

After a user enters a string of digits, the Python code is to replace the 5 with a 0, but I have not been able to overcome errors in syntax. I tried reading the reference on if statements but was unable to identify the issue. Thank you.

string = input('Enter a string of digits: ')
length_of_string = len(string)
counter = 0
while (counter <= length_of_string):
    {
       if string[counter] == '5':
           string[counter] = '0'
           counter = counter + 1
       else:
           counter = counter + 1
           continue
    }
File "<ipython-input-37-154bb43ba751>", line 15
    if string[counter] == '5':
                             ^
SyntaxError: invalid syntax
wjandrea
  • 28,235
  • 9
  • 60
  • 81
cielo_azzuro
  • 89
  • 1
  • 9
  • 5
    Python does not use brackets (`{}`) for code blocks. Just indent it with 4 spaces. – Asocia Jul 23 '20 at 16:40
  • 2
    ```>>> from __future__ import braces SyntaxError: not a chance``` – Asocia Jul 23 '20 at 16:41
  • 1
    In Python, a string is immutable. You cannot overwrite the values of immutable objects. `string[counter] = '0'` will raise `TypeError: 'str' object does not support item assignment`. Use `replace()` instead. – nguyendhn Jul 23 '20 at 16:50

1 Answers1

1

You only want to replace those '0' with '5' ? Is this what you are looking for?

string = input('Enter a string of digits: ')
replaced_string = string.replace('5', '0')
print(replaced_string)

Here is another solution for you with for loop and if statements:

string = input('Enter a string of digits: ')
replaced_string = ""
for char in string:
    if char == "5":
        replaced_string += "0"
    else:
        replaced_string += char
print(replaced_string)
MisterNox
  • 1,445
  • 2
  • 8
  • 22