簡體   English   中英

比較Python中的兩個變量

[英]Comparing two variables in Python

我正在這里測試a和b的相等性。 我不確定為什么即使a和b都等於“ 75”(相同的值),輸出也輸出“不等於”。

a = (len(products)) #products is a dictionary, its length is 75
b = (f.read()) #f is a txt file that contains only '75'

if(str(a) == str(b)):
    print ('equal')
else:
    print ('not equal')

f.read() int()周圍添加一個int()以將str類型轉換為一個int

>>> b = f.read().strip() # call strip to remove unwanted whitespace chars
>>> type(b)
<type 'str'>
>>>
>>> type(int(b))
<type 'int'>
>>>
>>> b = int(b)

現在,您可以將ab與具有相同類型值的知識進行比較。

文件內容總是以字符串/字節返回,因此您需要相應地轉換/鍵入大小寫。

“ a”的值為75的整數,而“ b”的值為“ 75”的字符串。 當計算是否相等時,結果將為假,因為它們不是同一類型。 嘗試使用以下方法將b強制轉換為整數:

b = int(b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM