我想用短划线(–
)代替长划线(-
)。我的代码:
if " – " in string:
string = string.replace(" – ", " - ")
导致以下错误:
SyntaxError:文件./script.py中第76行的非ASCII字符'\ xe2',但未声明编码;有关详情,请参见http://www.python.org/peps/pep-0263.html
我该如何解决?
长破折号不是ASCII character。声明脚本的编码,例如((top on top):
#-*- coding: utf-8 -*-
utf-8
以外还有其他编码,但是如果不使用几乎覆盖所有(unicode)字符的ASCII字符,使用utf-8
总是很安全的。
请参阅PEP 0263了解更多信息。
我想链接另一个答案:https://stackoverflow.com/a/42856932/3751268。但是,这仅适用于Python 2。
这是python 3的解决方案:
my_str = '—asasas—'
my_str.replace(b'\xe2\x80\x94'.decode('utf-8'), '--')