您没有累加器来保存输出,并且计数器上的逻辑关闭。以下循环遍历字符串并将字符连接到输出,除非字符索引是在给定字符的哪一点给出的索引。
def SSet(s, i, c):
"""A copy of the string 's' with the character in position 'i' set to character 'c'"""
res = ""
count = -1
for item in s:
count += 1
if count == i:
res += c
else:
res += item
return res
print(SSet("Late", 3, "o"))
打印
Lato
这可以罗列其去除反写更好:
def SSet(s, i, c):
"""A copy of the string 's' with the character in position 'i' set to character 'c'"""
res = ""
for index, item in enumerate(s):
if index == i:
res += c
else:
res += item
return res
它也通过附加字符的列表,然后加入进行得更快他们在最后:
def SSet(s, i, c):
"""A copy of the string 's' with the character in position 'i' set to character 'c'"""
res = []
for index, item in enumerate(s):
if index == i:
res.append(c)
else:
res.append(item)
return ''.join(res)
它也没有提出的对,但这里是如何与切片做到这一点:
def SSet(s, i, c):
"""A copy of the string 's' with the character in position 'i' set to character 'c'"""
return s[:i]+c+s[i+1:]
这是完美的,非常感谢所有不同的方法。 – Tigerr107