如何摆脱字符串中的某些字符?.replace()不起作用

烦恼

我需要摆脱从xml文件中获得的字符串中的波兰字符。我使用.replace(),但是在这种情况下不起作用。为什么?编码:

# -*- coding: utf-8
from prestapyt import PrestaShopWebService
from xml.etree import ElementTree

prestashop = PrestaShopWebService('http://localhost/prestashop/api', 
                              'key')
prestashop.debug = True

name = ElementTree.tostring(prestashop.search('products', options=
{'display': '[name]', 'filter[id]': '[2]'}), encoding='cp852',  
method='text')

print name
print name.replace('ł', 'l')

输出:

Naturalne mydło odświeżające
Naturalne mydło odświeżające

但是,当我尝试替换非波兰字符时,效果很好。

print name
print name.replace('a', 'o')

结果:

Naturalne mydło odświeżające
Noturolne mydło odświeżojące

这也可以:

name = "Naturalne mydło odświeżające"
print name.replace('ł', 'l')

有什么建议吗?

马克·托洛宁

您正在将编码与字节字符串混合在一起。这是一个重现此问题的简短示例。我假设您正在Windows控制台中运行,该控制台默认为cp852

#!python2
# coding: utf-8
from xml.etree import ElementTree as et
name_element = et.Element('data')
name_element.text = u'Naturalne mydło odświeżające'
name = et.tostring(name_element,encoding='cp852', method='text')
print name
print name.replace('ł', 'l')

输出(无替代):

Naturalne mydło odświeżające
Naturalne mydło odświeżające

原因是,name字符串是在中编码的,cp852但字节串常量'ł'是在的源代码编码中编码的utf-8

print repr(name)
print repr('ł')

输出:

'Naturalne myd\x88o od\x98wie\xbeaj\xa5ce'
'\xc5\x82'

最好的解决方案是使用Unicode字符串:

#!python2
# coding: utf-8
from xml.etree import ElementTree as et
name_element = et.Element('data')
name_element.text = u'Naturalne mydło odświeżające'
name = et.tostring(name_element,encoding='cp852', method='text').decode('cp852')
print name
print name.replace(u'ł', u'l')
print repr(name)
print repr(u'ł')

输出(已进行替换):

Naturalne mydło odświeżające
Naturalne mydlo odświeżające
u'Naturalne myd\u0142o od\u015bwie\u017caj\u0105ce'
u'\u0142'

请注意,Python 3et.tostring具有Unicode选项,默认情况下字符串常量为Unicode。repr()字符串版本也更具可读性,但是ascii()实现了旧的行为。您还会发现Python 3.6甚至可以在不使用波兰语代码页的控制台上打印波兰语,因此也许根本不需要替换字符。

#!python3
# coding: utf-8
from xml.etree import ElementTree as et
name_element = et.Element('data')
name_element.text = 'Naturalne mydło odświeżające'
name = et.tostring(name_element,encoding='unicode', method='text')
print(name)
print(name.replace('ł','l'))
print(repr(name),repr('ł'))
print(ascii(name),ascii('ł'))

输出:

Naturalne mydło odświeżające
Naturalne mydlo odświeżające
'Naturalne mydło odświeżające' 'ł'
'Naturalne myd\u0142o od\u015bwie\u017caj\u0105ce' '\u0142'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章