繁体   English   中英

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

[英]Python: Can't compare concatenated Strings with regular Strings

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

文件看起来像这样: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?"

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

n = f.readline()

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

bottomn = "B" + str(n)

给你bottomn = 'B4\n' 该字符串本身等于'B4'

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

如果这不能回答您的问题,您将需要提出一个更清晰的问题,最好是包含最小的完整可验证示例的问题。 另外——请更好地格式化您的代码。 编辑框中有一个代码格式化工具。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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