我需要从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')
输出:
^{2}$但当我试图取代非波兰字符,它工作得很好。在
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')
有什么建议吗?在
您正在将编码与字节字符串混合在一起。下面是一个简单的工作示例,再现了这个问题。我假设您在一个默认为
cp852
编码的Windows控制台中运行:输出(不更换):
^{pr2}$原因是,}的源代码编码的。在
name
字符串编码在cp852
中,而字节字符串常量'ł'
是用{输出:
最好的解决方案是使用Unicode字符串:
输出(更换):
注意python3的
et.tostring
有一个Unicode选项,字符串常量默认为Unicode。字符串的repr()
版本也更可读,但是ascii()
实现了旧的行为。您还将发现python3.6甚至可以在不使用波兰语代码页的控制台上打印波兰语,所以您可能根本不需要替换这些字符。在输出:
如果我正确理解您的问题,您可以使用^{} :
您可能需要先用
name.decode('utf_8')
对cp852编码的字符串进行解码。在相关问题 更多 >
编程相关推荐