gpt4 book ai didi

python - 类型错误 : 'str' object does not support item assignment (Python)

转载 作者:太空狗 更新时间:2023-10-30 02:29:23 25 4
gpt4 key购买 nike

这就是我想要做的:

输入:ABCDEFG

期望的输出:

***DEFG
A***EFG
AB***FG
ABC***G
ABCD***

这是我写的代码:

def loop(input):
output = input
for index in range(0, len(input)-3): #column length
output[index:index +2] = '***'
output[:index] = input[:index]
output[index+4:] = input[index+4:]
print output + '\n'

但我收到错误:TypeError: 'str' object does not support item assignment

最佳答案

您不能修改字符串的内容,您只能用更改创建一个新的字符串。所以你想要这样的东西而不是上面的函数

def loop(input):
for index in range(0, len(input)-3): #column length
output = input[:index] + '***' + input[index+4:]
print output

关于python - 类型错误 : 'str' object does not support item assignment (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com