2016-11-18 6 views
1

私はインデックスを使用せずにこれを試してみたいと思います。特定の位置の文字列内の文字を別の文字に設定しようとしています

def SSet(s, i, c): 
#A copy of the string 's' with the character in position 'i' 
#set to character 'c' 
count = -1 
for item in s: 
    if count >= i: 
     count += 1 
    if count == i: 
     item += c 
print(s) 

print(SSet("Late", 3, "o")) 

この例では、LateをLatoに変更する必要があります。

ありがとうございます。

答えて

1

出力を保持するアキュムレータがなく、カウンタのロジックがオフでした。次のコードは文字列をループし、文字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:] 
+0

これは完璧です、どうもありがとうございました。 – Tigerr107

1
def SSet(s, i, c): 
#A copy of the string 's' with the character in position 'i' 
#set to character 'c' 
    count = 0 
    strNew="" 
    for item in s: 
     if count == i: 
      strNew=strNew+c 
     else: 
      strNew=strNew+item 
     count=count+1 

    return strNew 

print(SSet("Late", 3, "o")) 
関連する問題