字符串编码/解码问题 - 从末尾缺少字符

use*_*260 5 python encode pyodbc netezza python-2.7

NVARCHAR在我的数据库中有类型列.我无法在我的代码中将此列的内容转换为纯字符串.(我pyodbc用于数据库连接).

# This unicode string is returned by the database
>>> my_string = u'\u4157\u4347\u6e65\u6574\u2d72\u3430\u3931\u3530\u3731\u3539\u3533\u3631\u3630\u3530\u3330\u322d\u3130\u3036\u3036\u3135\u3432\u3538\u2d37\u3134\u3039\u352d'

# prints something in chineese 
>>> print my_string
??????????????????????????
Run Code Online (Sandbox Code Playgroud)

我离开的最近的是通过将其编码utf-16为:

>>> my_string.encode('utf-16')
'\xff\xfeWAGCenter-04190517953516060503-20160605124857-4190-5'
>>> print my_string.encode('utf-16')
??WAGCenter-04190517953516060503-20160605124857-4190-5
Run Code Online (Sandbox Code Playgroud)

但是,根据数据库中的值存储,我需要的实际值是:

WAGCenter-04190517953516060503-20160605124857-4190-51
Run Code Online (Sandbox Code Playgroud)

我试图用编码它utf-8,utf-16,ascii,utf-32但似乎没有任何工作.

有没有人知道我错过了什么?以及如何从中获得所需的结果my_string.

编辑:在转换为utf-16-le,我能够从开始删除不需要的字符,但仍然从一端丢失一个字符

>>> print t.encode('utf-16-le')
WAGCenter-04190517953516060503-20160605124857-4190-5
Run Code Online (Sandbox Code Playgroud)

在尝试其他一些列时,它正在工作.这个间歇性问题的原因可能是什么?

Ser*_*sta 2

您的数据库定义、在其中存储值的方式或从中读取值的方式存在主要问题。我只能解释您所看到的内容,但不能解释原因或如何解决它,除非:

  • 数据库的类型
  • 您在其中输入值的方式
  • 提取值以获得伪 unicode字符串的方式
  • 如果您使用直接(本机)数据库访问,则为实际内容

您得到的是一个 ASCII 字符串,其中 8 位字符按对分组,以小端顺序构建 16 位 unicode 字符。由于预期字符串包含奇数个字符,最后一个字符在翻译过程中(无法挽回地)丢失,因为原始字符串以u'\352d'0x2d 为 ASCII 码结尾'-',0x35 为'5'. 演示:

def cvt(ustring):
    l = []
    for uc in ustring:
        l.append(chr(ord(uc) & 0xFF)) # low order byte
        l.append(chr((ord(uc) >> 8) & 0xFF)) # high order byte
    return ''.join(l)

cvt(my_string)
'WAGCenter-04190517953516060503-20160605124857-4190-5'
Run Code Online (Sandbox Code Playgroud)