2016-07-12 3 views
3

나는 string.replace("x", "y") 메서드를 알고 있지만 파이썬 및 프로그래밍 전반을 더 잘 이해할 수 있도록 문자열에서 문자를 수동으로 제거하려고합니다. 현재 가지고있는 방법은 아래에 나와 있습니다. 그러나 "Dee"와 "e"를 제거하는 이유는 "De"를 반환하지만 "John Do"와 "o"를 제거하면 "Jhn D"가 반환됩니다. . 따라서 두 개의 문자를 제거하지만 첫 번째 문자는 하나만 제거합니다.Python - 수동으로 문자열에서 특정 문자 제거

도움을 주시면 감사하겠습니다.

def remove_letter(): # Remove a selected letter from a string 
    base_string = str(raw_input("Enter some text: ")) 
    letter = str(raw_input("Enter the letter to remove: ")) # takes any string size 
    letter = letter[0] # ensures just one character is used 
    length = len(base_string) 
    location = 0 

    while location < length: 
     if base_string[location] == letter: 
      base_string = base_string[:location] + base_string[location+1::] 
      # concatenate string using slices 
      length -= 1 
     location += 1 

    print("Result %s" % base_string) 
+9

엉망인 것은 두 개의 _adjacent_ 문자를 제거하는 것입니다. 'location'에서 캐릭터를 제거 할 때'location'에 무슨 일이 일어나는지 생각해보십시오. – khelwood

답변

3

문제의 오유가이 편지를 제거하는 동안 당신은, 당신의 편지를 제거 할 문자열의 크기를 변경할 수 있다는 것입니다 :
당신이 디에서 처음으로 '전자'를 제거하면, 당신은 위치를 가지고 = 1, 첫 번째 'e'에 해당하지만 두 번째 'e'의 첫 번째 'e'가됩니다. e를 제거한 후, 현재 루프의 끝에서 location = 2이고 length = 2이므로 루핑을 중단하십시오.

어떻게 문제를 해결하려면 : 당신이 편지를 찾을 수없는 경우에만 위치를 증가 :

else: 
    location += 1 

이 잘 제거 된 편지 후 편지를 확인하지에서 루프를 방지 할 수 있습니다.

더 자세한 설명이 필요하면 질문하십시오.

+0

감사합니다. 나는 그것에 대해 생각해 봤어야 했어. – user2931871

2

khelwood 것을 고려하고 HolyDanna는이 가능한 방법이 될 수 말했다

def removeletter(string, letter): 
    out = '' 
    for i in string: 
     if not i == letter: 
      out += i 
    return out 

altered_string = removeletter(string, letter) 

편집 - 당신은 쉽게하지만 단일 문자의 경우, str.replace() 방법처럼이 작업을 확장 할 수 :

def stringreplace(string, letter, replacement): 
    out = '' 
    for i in string: 
    if i == letter: 
     out += replacement 
    else: 
     out += i 
    return out 

altered_string = stringreplace(string, letter, replacement)