您沒有累加器來保存輸出,並且計數器上的邏輯關閉。以下循環遍歷字符串並將字符連接到輸出,除非字符索引是在給定字符的哪一點給出的索引。
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