【问题标题】:python: copy+paste apostrophe from internet gives me a strange errorpython:从互联网复制+粘贴撇号给我一个奇怪的错误
【发布时间】:2013-09-07 19:50:19
【问题描述】:

我需要能够在我的代码中使用来自网站的复制+粘贴字符串。该网站的编码是 unicode (utf-8)。字符串

'''I’ve held others before''' 

是复制+粘贴的,并且有一个“有趣”的撇号。当我尝试替换这个撇号时

my_string = '''I’ve held others before'''

my_string.replace('’', "'")
print(my_string)

我还是明白了

>>> I’ve held others before

而不是

>>> I've held others before

我不能使用带有有趣撇号的字符串,因为稍后在我的代码中它会给我这个错误:

'ascii' codec can't decode byte 0xe2 in position 2: ordinal not in range(128)

我尝试添加两者

my_string.decode('utf-8')
my_string.encode('utf-8')

但他们似乎什么也没做。有什么想法吗?

【问题讨论】:

标签: python string utf-8 ascii


【解决方案1】:

字符串在python中是不可变的,你需要将str.replace的结果重新赋值给变量。

>>> my_string = '''I’ve held others before'''
>>> my_string = my_string.replace('’', "'")
>>> my_string
"I've held others before"

unicode 字符串最好使用u'...' 前缀:

>>> u'''Joey’s house'''.replace(u'’', "'")
"Joey's house"

在文件顶部添加此行以消除这些解码错误:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多