Python dictionary str() 方法用于检索字典的字符串表示形式。
在 Python 中,字符串是一种不可变的数据类型。字符串是 Python 中用双引号或单引号括起来的任何文本,包括字母、特殊字符和数字。在所有编程语言中,这种数据类型是最普遍的。
语法
以下是 Python 字典 str() 方法的语法 -
str(dict)
参数
- dict − 这是字典。
返回值
此方法返回字典的字符串表示形式。
例以下示例显示了 Python dictionary 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'}}]
The equivalent string is: [{'Universe': {'Planet': 'Earth'}}]