出力を保持するアキュムレータがなく、カウンタのロジックがオフでした。次のコードは文字列をループし、文字indexが指定された文字を使用したときのインデックスでない限り、文字を出力に連結します。
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)
それはまたのためにunaskedであるが、ここでスライスしてそれを行う方法である:すべての異なる方法について
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