【问题标题】:code runs from interpreter but not in editor代码从解释器运行,但不在编辑器中
【发布时间】:2019-01-31 20:58:41
【问题描述】:

我正在尝试向文本文件中添加一些符号,我无法在编辑器中定义这些符号 但它可以从命令行运行。

symbols = '$¢£¥€¤' 在解释器中工作,但在编辑器(崇高)中工作,但是它不能在命令中正确打印这些符号。但是如果我 decode("utf-8") 然后打印工作正常。

symbols = '$¢£¥€¤'
s=symbols.decode("utf-8")

我使用 python 2.7 和 sublime 文本编辑器

这是我使用编辑器运行时遇到的错误

SyntaxError: Non-ASCII character '\xc2' in file /home/programmer/Desktop/seleniumIns.py on line 184, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

如何解决这些问题以将它们添加到我在编辑器中的原始程序中

【问题讨论】:

  • “命令中没有正确打印这些符号”是什么意思?
  • 您的文件顶部是否还有# -*- coding: utf-8 -*- 之类的内容,Sublime 是否将其保存为 UTF8?
  • @RemcoGerlich 我得到的是 � 而不是实际字符(除了 $ 可以正常打印)
  • @AmjasdMasdhash,如果你是 Python 初学者,你绝对应该切换到 Python 3。在那里,你可以省略 # coding: utf-8 声明(因为 UTF-8 是默认的源代码编码)和还有.decode('utf8') 部分(因为字符串是Unicode 字符串)。
  • @lenz 我已经使用 python 一年多了,python 2 可以在 unicodestr 之间有所不同,这与 python 3 不同,还有 print "Hello world" 而不是 print ("Hello world") :-D

标签: python unicode


【解决方案1】:

当你运行一个包含 unicode 的 python 文件时,你需要告诉解释器使用什么编码。 在您的情况下,将这一行放在脚本的第一行:

# -*- coding: utf-8 -*-

您将能够使用 utf-8!

【讨论】:

  • 这行得通,每当我使用它们时,我都必须使用decode("utf-8")
  • decode("utf-8") 将为您提供 Unicode 字符串的 8 位字符串版本。看看this paragraph
  • @edwinburton 正好相反:'...'.decode('utf8') 将 8 位字符串转换为 Unicode 字符串。
猜你喜欢
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
相关资源
最近更新 更多