Search code examples
pythonlistfilesys

Python: Can't compare concatenated Strings with regular Strings


The opponentCorner Function is supposed to return a move(String). N is a positive Integer in this case 4. It is the first line of the file. The problem is that I get "Whats going on"(None) as a output when I try to compare the opponentsFirstTurn(read from File. In this case "B4") with concatenated String(the variables in bold). I also tried to compare via the list index(corners[1], corners[3] etc.) and cast to string but I still get the same issue. But I get the correct output when I compare with the normal Strings("B1", "T1", "R1", "L1")

the File looks like this: 4 B4

path = "C:\hello.txt" with open(path, mode="r") as f:

n = f.readline()
opponentFirstTurn= f.readline()


**count = len(open(path).readlines(  ))
topn = "T" + str(n)
bottomn = "B" + str(n)
leftn = "L" + str(n)
rightn = "R" + str(n)**

corners = ["T1", topn, "B1", bottomn, "R1", rightn, "L1", leftn]


print(rightn)



print(n)
print(opponentFirstTurn)




#T1 correct output, R4 whats going on, B1 correct output although leftn(concatenated String)

def opponentCorner()-> str:

    global opponentFirstTurn
    global corners

    if opponentFirstTurn == "T1":
        #play L1 first Turn, than always Rn
        #nextMove = rightn
        return "L1" 
    elif opponentFirstTurn== topn:

        #play R1 first turn, then always Ln
        #nextMove = leftn
        return "R1" 

    elif opponentFirstTurn == "B1":
        #play Ln first turn, then always R1
        #nextMove = "R1"
        return leftn 

    elif opponentFirstTurn== bottomn:
        #play Rn first turn, then always L1
        #nextMove = "L1"
        return rightn

    elif opponentFirstTurn == "R1":
        #play Tn first turn, then always B1
        #nextMove = "B1"
        return topn 

    elif opponentFirstTurn == corners[5]:
        #play Bn first turn, then always T1
        #nextMove = "T1"
        return bottomn

    elif opponentFirstTurn == "L1":
        #play T1 first turn, then always Bn
        #nextMove = bottomn
        return "T1" 

    elif opponentFirstTurn== leftn:
        #play B1 first turn, then always Tn
        #nextMove = topn
        return "B1"
    else: 
        return "Whats going on?"

Solution

  • The readline method keeps any trailing newline character as part of the string. Thus, after

    n = f.readline()
    

    n will be the string '4\n'. Since this is already a string, str(n) is pointless and

    bottomn = "B" + str(n)
    

    gives you bottomn = 'B4\n'. This string is not equal to 'B4' by itself.

    You could use n = f.readline().strip() to strip off that newline character.

    If that doesn't answer your question, you would need to ask a clearer question, preferably one that contains a minimal complete verifiable example. Also -- please format your code better. There is a code formatting tool in the edit box.