Python: 无法将串联字符串与常规字符串进行比较

Python: Can't compare concatenated Strings with regular Strings

对手角函数应该return 移动(字符串)。在本例中 N 是一个正整数 4。它是文件的第一行。 问题是,当我尝试将 opponentsFirstTurn(从文件中读取。在本例中为“B4”)与连接字符串(变量以粗体显示)进行比较时,我得到“发生了什么”(None)作为输出。 我还尝试通过列表索引(corners[1]、corners[3] 等)进行比较并转换为字符串,但我仍然遇到同样的问题。 但是当我与普通 Strings("B1", "T1", "R1", "L1")

比较时,我得到了正确的输出

文件如下所示: 4个 B4

path = "C:\hello.txt" 打开(路径,模式=“r”)作为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?"

readline 方法将任何尾随的换行符保留为字符串的一部分。因此,在

之后
n = f.readline()

n 将是字符串 '4\n'。因为这已经是一个字符串,所以 str(n) 没有意义并且

bottomn = "B" + str(n)

给你bottomn = 'B4\n'。这个字符串本身等于'B4'

您可以使用 n = f.readline().strip() 去除换行符。

如果这不能回答您的问题,您需要提出一个更明确的问题,最好是包含 minimal complete verifiable example 的问题。另外——请更好地格式化您的代码。编辑框内有代码格式化工具