Python,用短破折号代替长破折号?

问题描述 投票:10回答:2

我想用短划线()代替长划线(-)。我的代码:

if " – " in string:
      string = string.replace(" – ", " - ")

导致以下错误:

SyntaxError:文件./script.py中第76行的非ASCII字符'\ xe2',但未声明编码;有关详情,请参见http://www.python.org/peps/pep-0263.html

我该如何解决?

python replace python-2.x
2个回答
12
投票

长破折号不是ASCII character。声明脚本的编码,例如((top on top)

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

utf-8以外还有其他编码,但是如果不使用几乎覆盖所有(unicode)字符的ASCII字符,使用utf-8总是很安全的。

请参阅PEP 0263了解更多信息。


0
投票

我想链接另一个答案:https://stackoverflow.com/a/42856932/3751268。但是,这仅适用于Python 2。

这是python 3的解决方案:

my_str = '—asasas—'
my_str.replace(b'\xe2\x80\x94'.decode('utf-8'), '--')
© www.soinside.com 2019 - 2024. All rights reserved.