2017-12-19 11 views
0

내 코드는 목록으로 분리 된 문자열을 반복하고 모든 이전 발생을 새 것으로 바꾼 다음 문자열을 반환합니다. 귀하의 채널이 동일한 오래된 않는 경우한 건의 해지

def replace(s, old, new): 
    ch="" 
    i=0 
    newMsg=s.split() 
    print newMsg 
    for ch in newMsg: 
     if ch==old: 
      newMsg[i]=newMsg[i].replace(old, new) 
     else: 
      i = i +1 
    return ' '.join(newMsg) 
+1

왜 's.replace (old, new)'가 아닌가? – DJK

+0

죄송합니다. < –

답변

2

, i가 증가하지 뭐 때문에 : 그러나 내 문제는 첫 번째 발생이 계산되고, 다른 사람이 동일하게 유지 될 것으로 보인다는 것이다. 이런 식으로 고칠 수 있습니다.

def replace(s, old, new): 
    ch="" 
    i=0 
    newMsg=s.split() 
    print newMsg 
    for ch in newMsg: 
     if ch==old: 
      newMsg[i]=newMsg[i].replace(old, new) 
      i=i+1 
     else: 
      i = i +1 
    return ' '.join(newMsg) 

그렇다고해서 그렇게 할 필요는 없습니다. 열거 형을 사용할 수 있습니다.

def replace(s, old, new): 
    ch="" 
    newMsg=s.split() 
    print newMsg 
    for i,ch in enumerate(newMsg): 
     if ch==old: 
      newMsg[i]=newMsg[i].replace(old, new) 
    return ' '.join(newMsg) 
+0

또는 'else' 문을 완전히 제거하고'i = i + 1'을 들여 쓰지 않을 수 있습니다. –

+0

@ sam-pyt yea 또는 그 – SuperStew