所以我已经使用Python很长一段时间了,我总是使用以下结构来打印变量:
dt = 5.5
print("dt = " + str(dt))
但我知道这个命令有一个更优雅的版本:
dt = 5.5
print("dt = %f" % dt)
但我不断得到错误:
Traceback (most recent call last):
File "C:\Users\Komputer\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2980, in run_code
self.showtraceback(running_compiled_code=True)
File "C:\Users\Komputer\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 1849, in showtraceback
self.showsyntaxerror(filename, running_compiled_code)
File "C:\Users\Komputer\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 1911, in showsyntaxerror
stb = self.SyntaxTB.structured_traceback(etype, value, elist)
File "C:\Users\Komputer\Anaconda3\lib\site-packages\IPython\core\ultratb.py", line 1408, in structured_traceback
newtext = linecache.getline(value.filename, value.lineno)
File "C:\Users\Komputer\Anaconda3\lib\linecache.py", line 16, in getline
lines = getlines(filename, module_globals)
File "C:\Users\Komputer\Anaconda3\lib\linecache.py", line 47, in getlines
return updatecache(filename, module_globals)
File "C:\Users\Komputer\Anaconda3\lib\linecache.py", line 137, in updatecache
lines = fp.readlines()
File "C:\Users\Komputer\Anaconda3\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 83: invalid continuation byte
有什么不对?我想这是文本编解码器,但我不知道在哪里更改它。打印其他类型的变量时会出现相同的错误。我已经查看了出现此错误的几个问题,但没有一个是关于打印的。
我正在使用Spyder 3.2.8(Python 3.6)
错误不在您发布的命令中;您的Python源文件只包含非UTF8字符。查找任何特殊字符,并查看您编写的文本编辑器是否有选择字符编码的选项。
编辑:在latin1字符集中,字节0xf3
代表ó
,所以也许检查你是否在任何地方使用该字符...
非常感谢!你们是对的,我有相似但不一样的代码,其中包含印刷中的“ó”字母。
有趣的是你可以用print("ó")
打印“ó”,但你不能通过在print("ó" +str(dt))
或print("ó %f" %dt)
这样的“print”中添加变量来实现。