Удаление указанного c элемента в строках? - PullRequest
0 голосов
/ 29 февраля 2020

Таким образом, проблема в том, что я пытаюсь вынуть каждую букву в ana2 как i go при проверке анаграммы. Но когда я заменяю предмет, он вытаскивает ВСЕ эту букву из анаграммы, поэтому, когда он достигает 2-й буквы, он останавливается. Любая помощь будет принята с благодарностью.

clue2 = "S#tatue# of Libert#y"
clue3 = "T#om Mar##volo R#iddle#"

CLUE1 = clue1.upper().replace("#",'').replace(" ",'')
CLUE2 = clue2.upper().replace("#",'').replace(" ",'')
CLUE3 = clue3.upper().replace("#",'').replace(" ",'')

print("CLUE1 is",CLUE1)
print("CLUE2 is",CLUE2)
print("CLUE3 is",CLUE3)

ana1 = "HERECOMEDOTS" #stores hypothesis in constant
ana2 = "BUILDTOSTAIFREE"
ana3 = "IIMLORDVOLDEMORT"
print()

print('Testing Hypothesis 1 HERECOMEDOTS')

for item in CLUE1 : #executes a for loop that compares character by character of each word to see if they contain the same. 
    if item in ana1:
        print(item, "in clue is in my hypothesis. Continue.") #if else statements to print the according statements if conditions are met 
    else:
        print(item, "in the clue is NOT in my hypothesis. Thus, my hypothesis is false.\nCLUE1 is NOT an anagram!")

print('CLUE1 is an anagram!')

print() #spaces for desired output

print('Testing Hypothesis 2 BUILDTOSTAIFREE')

for item in CLUE2 :
    if item in ana2:
        ana2 = ana2.replace(item,'')
        print(item, "in clue is in my hypothesis. Continue.")
    else:
        print(item, "in the clue is NOT in my hypothesis. Thus, my hypothesis is false.\nCLUE2 is NOT an anagram!")
        break

print()
print('Testing Hypothesis 3 IIMLORDVOLDEMORT')

for item in CLUE3 :
    if item in ana3:
        print(item, "in clue is in my hypothesis. Continue.")
    else:
        print(item, "in the clue is NOT in my hypothesis. Thus, my hypothesis is false.\nCLUE3 is NOT an anagram!")
        break``

1 Ответ

0 голосов
/ 29 февраля 2020

Функция replace() имеет необязательный параметр count, который позволяет ограничить количество замен. Установите значение 1, чтобы заменить только первое совпадение.

        ana2 = ana2.replace(item,'', 1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...