[英]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.