Python 字典 str() 方法



Python 字典 str() 方法用於獲取字典的字串表示形式。

在 Python 中,字串是一種不可變資料型別。字串是 Python 中用雙引號或單引號括起來的任何文字,包括字母、特殊字元和數字。在所有程式語言中,這種資料型別是最常見的。

語法

以下是 Python 字典 str() 方法的語法:

str(dict)

引數

  • dict − 這是字典。

返回值

此方法返回字典的字串表示形式。

示例

以下示例演示了 Python 字典 str() 方法的用法。這裡建立一個字典 'dict'。然後使用 str() 方法獲取字典的字串表示形式。

# Creating a dictionary
dict = {'Name': 'Zara', 'Age': 7};
# Printing the result
print ("Equivalent String : %s" % str (dict))

執行以上程式,會產生以下結果:

Equivalent String : {'Name': 'Zara', 'Age': 7}

示例

在這裡,我們建立了一個空字典。然後使用 str() 方法返回空字典的等效字串表示形式。

# Creating an empty dictionary
dict_1 = {};
res = str(dict_1)
# Printing the result
print ("The equivalent string is: ", res)

以下是上述程式碼的輸出:

The equivalent string is:  {}

示例

在下面的示例中,我們建立了一個巢狀字典的列表。然後使用 str() 方法返回字典的等效字串表示形式。

dict_1 = [{'Universe' : {'Planet' : 'Earth'}}]
print("The dictionary is: ",dict_1)
# using str() method
result = str(dict_1)
print("The equivalent string is: ", result)

上述程式碼的輸出如下:

The dictionary is: [{'Universe': {'Planet': 'Earth'}}]
The equivalent string is: [{'Universe': {'Planet': 'Earth'}}]
python_dictionary.htm
廣告
© . All rights reserved.