Python – 解包字符串中的值
给定一个字典,将它的值解包成一个字符串。
Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “Gfg”, 9 : “Best”}
Output : First value is Gfg Second is Best
Explanation : After substitution, we get Gfg and Best as values.
Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “G”, 9 : “f”}
Output : First value is G Second is f.
Explanation : After substitution, we get G and f as values.
方法:使用 format() + * 运算符 + values()
上述功能的组合可以用来解决这个问题。在此,我们使用格式将所需值与字符串中的大括号进行映射。 *运算符用于解包和分配。这些值是使用 values() 提取的。
Python3
# Python3 code to demonstrate working of
# Unpacking Integer Keys in Strings
# Using format() + * operator + values()
# initializing string
test_str = "First value is {} Second is {} Third {}"
# printing original string
print("The original string is : " + str(test_str))
# initializing dictionary
test_dict = {3 : "Gfg", 4 : "is", 9 : "Best"}
# using format() for mapping required values
res = test_str.format(*test_dict.values())
# printing result
print("String after unpacking dictionary : " + str(res))
输出
The original string is : First value is {} Second is {} Third {}
String after unpacking dictionary : First value is Gfg Second is is Third Best