string = input() #input automatically returns a string, so there's no need for str()
y = '!' * (len(string)-5) + string[4:]print (y) #remember to print y, not string because y is the modified version of your string
def replace_chars(string, positions, s):
new_string = []
for i in range(len(string)):
if i not in positions: #Checking if position, i, is not one of the marked positions
new_string.append(string[i])
else: #If it is a marked positions, append it with the marker, s, or more specifically '@'
new_string.append(s)
return ''.join(new_string) #Make the list a string
代码正在打印未修改的x值。 您的代码逻辑正在使用结果创建一个新变量y,而x未被修改。 但是,您正在打印与输入完全相同的x值。 逻辑似乎正在运行,结果对于y的值是正确的
请检查一下。 如果有任何问题,请发布错误日志或结果
对于非常基本的直接解决方案,您可以执行以下操作:
对于这种方法更灵活的方法,您应该创建一个函数。假设给定了在列表中更改字符串的位置、字符串和替换
string[n]
的特定标记,这应该相当简单:这可以写在一个1-2行长的函数中,其中一行用于循环,但这种格式更便于可读性。但是如果你在1-2行中完成,它会是这样的:
相关问题 更多 >
编程相关推荐