3

我有 14 个字典,它们都包含相同的信息键(即时间、日期等),但值不同。我正在尝试构建一个函数,当字典被列为函数中的参数时,它将组合一个句子。

如果我有字典:

dic1 = {'Name': 'John', 'Time': 'morning'}

我想将它们连接到一个字符串:

print 'Hello ' + dic1['Name']+', good ' + dic1['Time']+ '.'

我该怎么办?

*注意,对不起,这会返回错误:

TypeError: can only concatenate list (not "str") to list
4

3 回答 3

6

我认为您的意思是interpolate,而不是concatenate

print "Hello %(Name)s, good %(Time)s" % dic1
于 2012-11-30T12:34:31.130 回答
2

使用新样式的字符串格式(python2.6 或更高版本):

print("Hello {Name}, good {Time}.".format(**dic1))

至于你的错误,我无法用你上面提供的代码来解释它。如果您尝试将__add__字符串添加到列表中,则会收到该错误:

>>> [45,3] + "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

但是将列表添加到字符串(如果您的字典将列表作为值,您将使用示例代码执行此操作)会产生稍微不同的错误:

>>> "foo" + [45,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'list' objects
于 2012-11-30T12:49:02.637 回答
-1
web_response = {2L: 67.0, 3L: 13.67, 4L: 10.25, 5L: 11.8, 6L: 11.83}

我有一个名为“web_response”的字典,对于字典与字符串的连接,我使用了逗号“,”

print "web_response=", web_response

输出:

web_response= {2L: 67.0, 3L: 13.67, 4L: 10.25, 5L: 11.8, 6L: 11.83}
于 2015-01-05T10:03:57.957 回答