【发布时间】:2023-03-23 00:00:01
【问题描述】:
用户输入一串数字后,Python代码是将5替换为0,但我一直无法克服语法错误。我尝试阅读the reference on if statements,但无法确定问题所在。谢谢。
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
【问题讨论】:
-
Python 不对代码块使用方括号 (
{})。只需缩进 4 个空格即可。 -
>>> from __future__ import braces SyntaxError: not a chance -
在 Python 中,字符串是不可变的。您不能覆盖不可变对象的值。
string[counter] = '0'将提高TypeError: 'str' object does not support item assignment。请改用replace()。
标签: python syntax syntax-error