繁体   English   中英

从python2转换为python3时处理encode()

[英]Handling encode() when converting from python2 to python3

我正在努力将一个大项目从python2转换为python3 (不需要python2向后兼容)。

在测试转换时,我发现我遇到了某些字符串被转换为bytes对象的问题,这导致了问题。 我将其追溯到以下方法,该方法在许多地方被调用:

def custom_format(val):
    return val.encode('utf8').strip().upper()

python2

custom_format(u'\xa0')
# '\xc2\xa0'
custom_format('bar')
# `BAR`

python3

custom_format('\xa0')
# b'\xc2\xa0'
custom_format('bar')
# b`BAR`

这是一个问题的原因是因为在某些时候, custom_format的输出意味着使用format()插入到SQL模板字符串中,但是'foo = {}'.format(b'bar') == "foo = b'BAR'" ,这会搞乱SQL语法的潜力。

简单地删除encode('utf8')部分将确保custom_format('bar')正确返回'BAR' ,但现在custom_format('\\xa0')返回'\\xa0'而不是'\\xc2\\xa0' python2版本。 (虽然我对unicode知之甚少,不知道这是不是坏事)

在不弄乱代码的SQLformat()部分的情况下,如何确保python3版本中展示python2版本的预期行为? 它是否像丢弃encode('utf8')一样简单,还是会导致意外冲突?

如果您的目的是确保所有传入的字符串,无论是str还是bytes ,都要转换为bytes ,那么您必须保持encode因为Python3使用str而不是bytes (Python2就是这种情况)作为本机字符串类型。 encodestr转换为bytes

如果您的目的是确保查询正确。 然后你可以删除encode ,让Python3为你处理事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM