簡體   English   中英

為什么這兩個字符串在 Python 中不相等?

[英]Why are these two strings not equal in Python?

我有一個簡單的 Python 代碼示例

import json
hello = json.dumps("hello")
print(type(hello))

if hello == "hello":
    print("They are equal")
else:
    print("They are not equal")

這是評估為“他們不相等”。 我不明白為什么這些值不相等。

我正在重新熟悉 Python,但我讀到這個“==”可以用作運算符來比較 Python 中的字符串。 我還打印了評估為“str”的 hello 類型

有人可以澄清一下嗎?

一旦打印出json.dumps()的結果,行為就會變得更加清晰:

print("hello", len("hello"))
print(hello, len(hello))

這輸出:

hello 5
"hello" 7

json.dumps()添加了額外的引號——你可以看到兩個字符串的長度不一樣。 這就是您的檢查失敗的原因。

json.dumps 用於將字典轉換為 json 字符串。 換句話說,它解釋導入並將其創建為 json 的等價物。 這意味着,將單個字符串放入將導致它被轉換為單個字符串的 json 等效項。

hello = json.dumps("hello")
print(hello)
 => "hello"

在 json 格式中,字符串用引號引起來,這就是 json.dumps() 將它放在引號中的原因。

print(json.dumps('hello'))

輸出-> "hello"

print('hello')

輸出-> hello

在此處輸入圖像描述

暫無
暫無

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

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