我有这段代码
Date = site.xpath('my xpath').extract()[0]
print "DDDDDDDDDDDDDDDDDDDDDD= "+Date
DateString = Date.split()
DayString = DateString[0]
MonthString = DateString[1]
Year = DateString[2]
Day = getDayOfDate(DayString)
Month = getMonthOfDate(MonthString)
print "Type Year = "+type(Year)
print "Month = "+Month+" Year = "+Year
我收到了这个错误
exceptions.TypeError: cannot concatenate 'str' and 'NoneType' objects
当我打印年份时,我得到2014
似乎Month
是无
这是例外
exceptions.TypeError: cannot concatenate 'str' and 'int' objects
答案 0 :(得分:3)
回到原来的答案:
Month is None
,因为您的函数没有正确拼写None
,因此函数返回"August"
。更好的功能是:
def getMonthFromDate(s):
months = ["January", "February", ...] # spell these correctly
for index, month in enumerate(months, 1):
if month in s:
return "{0:02d}".format(index)
raise ValueError
还是一个问题:
type(Year)
将返回type
个对象。您无法将其添加到字符串中。这正是错误信息(不是你给出的那个)告诉你的。尝试:
print "Type of Year: " + str(type(Year))
或者,因为与+
的连接字符串是unpythonic,类似于:
print "Type of Year: {}".format(type(Year))
这些也适用于错误三,你有一个int
。
你显然不知道Python已经做了所有这些:阅读datetime.strptime
。
答案 1 :(得分:2)
异常基本上说一个操作数是一个字符串 - 正如你所料 - 但另一个是None
。所以你试过'Month = ' + None
或类似的。因此,对于出现此错误的任何行,您在那里使用的变量似乎是None
而不是实际的字符串。
在您更新的问题中,错误消息突然显示为:
TypeError: cannot concatenate 'str' and 'type' objects
所以你现在试图将type
对象连接到一个字符串,这也暗示不起作用。您必须先将值转换为字符串:
print "Type Year = " + str(type(Year))
另一种方法是使用print语句的功能,该功能允许多个参数自动转换为字符串并自动连接:
print "Type Year =", type(Year)
答案 2 :(得分:1)
其中一个月/年似乎是无。从您提供的代码看来,最有可能是月
如果您使用了格式字符串(这是首选方式),就像这样
print "Month = {month} Year = {year}".format(month=Month, year=Year)
它不会导致异常,并立即清楚哪一个是None
答案 3 :(得分:0)
可能Year
很好,但Month
或Date
不是。考虑他们的价值观。