【问题标题】:Changing the value of a single number in a string to zero [duplicate]将字符串中单个数字的值更改为零[重复]
【发布时间】: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 个空格即可。
  • &gt;&gt;&gt; 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


【解决方案1】:

您只想将那些 '0' 替换为 '5' 吗? 这是你要找的吗?

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

下面是另一种使用 for 循环和 if 语句的解决方案:

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,这非常有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多