返回unicode字符串的前N个字符

Jon*_*ero 11 python unicode python-2.x

我有一个unicode字符串,我需要返回前N个字符.我这样做:

result = unistring[:5]
Run Code Online (Sandbox Code Playgroud)

但当然是unicode字符串的长度!=字符长度.有任何想法吗?唯一的解决方案是使用re?

编辑:更多信息

unistring = "?????????" #Metallica written in Greek letters
result = unistring[:1]
Run Code Online (Sandbox Code Playgroud)

返回 - >?

我认为unicode字符串是两个字节(char),这就是为什么会发生这种情况.如果我做:

result = unistring[:2]
Run Code Online (Sandbox Code Playgroud)

我明白了

M

哪个是正确的,那么,我应该总是切片*2还是应该转换成什么?

Tho*_*ers 7

当你说:

unistring = "?????????" #Metallica written in Greek letters
Run Code Online (Sandbox Code Playgroud)

没有 unicode字符串.你有一个字节串(大概)UTF-8.那不是一回事.unicode字符串是Python中的一个单独的数据类型.通过使用正确的编码解码字节串来获得unicode:

unistring = "?????????".decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

或者使用具有正确编码声明的源文件中的unicode文字

# coding: UTF-8
unistring = u"?????????"
Run Code Online (Sandbox Code Playgroud)

unicode字符串将在您执行时执行您想要的操作unistring[:5].

  • -1这是不正确的u“某些Unicode测试” [:5]可能给出非法序列,因为UTF-16是可变宽度编码,所以剪切“ Unicode”字符串不如剪切utf-8字符串正确 (2认同)

Ten*_*she 7

不幸的是,由于Python 3.0之前的历史原因,有两种字符串类型.byte strings(str)和Unicode strings(unicode).

在Python 3.0中统一之前,有两种方法可以声明字符串文字:unistring = "?????????"字节字符串,unistring = u"?????????"它是一个unicode字符串.

你看到的原因?,当你做result = unistring[:1]是因为一些在你的Unicode文本字符不能正确地在非Unicode字符串表示.如果您曾经使用过非常古老的电子邮件客户端并收到希腊等国家的朋友发来的电子邮件,您可能已经看到过这种问题.

因此,在Python 2.x中,如果需要处理Unicode,则必须明确地执行此操作.看一下在Python中处理Unicode的简介:Unicode HOWTO

  • 你是对的马克把它们称为字节串而不是ASCII字符串是更正确的,我已经相应地更新了答案.我真正想要表达的是,ASCII文本(或等效的字节字符串取决于您计算机上的代码页)是唯一可以使用字节字符串安全操作的东西. (2认同)