简体   繁体   中英

Iterating a string and replacing an element in python

I am attempting to search through two strings looking for matching elements. If the strings have two elements in common that are in different positions, I want to make that element in the 'guess' string a COW. If the strings have two elements in the same position, the element is a BULL.

Here is what I have:

        if index(number,i) in guess and not index(guess,i) == index(guess,i):
            replace(index(guess,i),'COW')

        if index(guess,i) == index(number,i):
            replace(index(guess,i),'BULL')

I'm not sure if I'm using index correctly.

First off, you need to be using index() and replace() as string methods, like Martijn said in a comment.

This would be like so: guess.index(i) to find the index of i in the string guess .

You might want to check out find() which will do the same as index() but won't raise an exception when the substring is not found.

Also note that you are seeing if the result of index() is in the string guess . That is an error, since an integer cannot be in a string! index() returns an integer!

Then consider that you are stating ... and not guess.index(i) == guess.index(i): (I fixed the index code) which makes no sense, since of course they are equal! They are the same thing!

Lastly, you are using replace incorrectly. From the documentation , replace takes a string as the first argument - not an index! Try using it like so: guess = guess.replace(i, 'BULL') . That will change guess to have all occurrences of i replaced by the string 'BULL' .

I wasn't concerned with you actual algorithm here, but just your basic errors.

I wouldn't use the index() method. Instead, I would turn the string's elements into a list, then say:

listOne = [hello,goodbye,adios, shalom]
listTwo = [hello,adios,arrivaderci]

def cowbull(L1, L2):
    for i in range(len(L1)):
        if L1[i] in L2:
            if L1[i] == L2[i]:
                L1[i] = 'BULL'
                L2[i] = 'BULL'
            else:
                L1[i] = 'COW'
                L2[L1[i]] = 'COW'

This is just how I would do it, but using the way you and William's code may work well also. I am just used to doing it this way, and it may very well be not as efficient as his, but it usually works very well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM