带有unicode的python 2.7 string.join()

thk*_*ang 12 python unicode

我有一堆包含unicode数据(在编码中)的字节字符串(str不是unicode在python 2.7中utf-8).

我试图加入他们(由"".join(utf8_strings)u"".join(utf8_strings))投掷

UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position 0: ordinal not in range(128)`
Run Code Online (Sandbox Code Playgroud)

有没有办法使用.join()非ascii字符串的方法?我确定我可以在for循环中连接它们,但这不符合成本效益.

Mar*_*ers 16

使用''.join()工作加入字节串就好了; 您看到的错误只会在您混合unicodestr对象时出现:

>>> utf8 = [u'\u0123'.encode('utf8'), u'\u0234'.encode('utf8')]
>>> ''.join(utf8)
'\xc4\xa3\xc8\xb4'
>>> u''.join(utf8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)
>>> ''.join(utf8 + [u'unicode object'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

使用Unicode值u''作为连接符并将Unicode字符串分别添加到要连接的字符串列表时,会引发上述异常.