python中print语句中的异常

时间:2016-11-22 05:06:49

标签: python

假设我在python中有一个print语句,如下所示:

print "components required to explain 50% variance : %d" % (count)

此语句提供ValuError,但如果我有print语句:

print "components required to explain 50% variance"

为什么会这样?

2 个答案:

答案 0 :(得分:7)

错误信息非常有用:

>>> count = 10
>>> print "components required to explain 50% variance : %d" % (count)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character 'v' (0x76) at index 35

所以python看到% v,它认为它是格式代码。但是,v不是受支持的格式字符,因此会引发错误。

修复一旦你知道它就很明显了 - 你需要转义不属于格式代码的%。你是怎样做的?添加另一个%

>>> print "components required to explain 50%% variance : %d" % (count)
components required to explain 50% variance : 10

请注意,您也可以使用.format,这在很多情况下更方便,更强大:

>>> print "components required to explain 50% variance : {:d}".format(count)
components required to explain 50% variance : 10

答案 1 :(得分:4)

应用于字符串的Sub CutandPaste() Dim i As Long Dim mainsheet As Worksheet Dim subsheet As Worksheet Set mainsheet = ActiveWorkbook.Sheets("Sheet1") Set subsheet = ActiveWorkbook.Sheets("Sheet2") With mainsheet endrow = .Range("A" & .Rows.Count).End(xlUp).Row For i = endrow To 25 Step -1 If .Cells(i, "J") <> "" Or .Cells(i, "L") <> "" Or .Cells(i, "N") <> "" Then .Rows(i).Resize(1, 15).Cut Destination:=subsheet.Cells(i + 56, "B") .Rows(i).Resize(1, 15).Delete '~~> if you want to delete End If Next End With End Sub 运算符会对字符串中的每个'%'执行替换。 '50%'未指定有效替代;只需在字符串中包含百分号,就必须加倍。