【问题标题】:Python: What's the equivalent of String[a:b] but for UnicodePython:什么是 String[a:b] 但对于 Unicode 的等价物
【发布时间】:2012-08-12 11:59:30
【问题描述】:

所以我有这样的事情:

x = "CЕМЬ"
x[:len(x)-1]

这是从字符串中删除最后一个字符。 但是它不起作用,它给了我一个错误。我想这是因为它是Unicode。那么如何对非 ansi 字符串进行这种简单的格式化。

【问题讨论】:

  • 为什么 unicode 是个问题?这看起来不像一个 unicode 字符串。除此之外:字符串是不可变的。
  • @Maulwurfn:因为它是 python 2 中的字节字符串,而不是 unicode 字符串,因此 OP 是切片字节,而不是字符。

标签: python string unicode string-formatting


【解决方案1】:

这是因为在 Python 2.x "CЕМЬ" 中,写 byte 字符串 b'C\xd0\x95\xd0\x9c\xd0\xac' 是一种奇怪的方式。

你想要一个 character 字符串。在 Python 2.x 中,字符串以 u: 为前缀:

x = u"CЕМЬ"
x[:-1] # Returns u"CЕМ" (len(x) is implicit for negative values)

如果您在程序中编写此代码(而不是交互式 shell),您将需要 specify a source code encoding。为此,只需将以下行添加到文件的开头,其中utf-8 与您的file encoding 匹配:

# -*- coding: utf-8 -*-

【讨论】:

  • 或使用 \uxxxx unicode 转义文字来表示任何不是 ASCII 字符(python 2)。在py3k中,默认的源码编码是UTF-8。
【解决方案2】:

使用utf-8编码保存文件:

# -*- coding: utf-8 -*-
x = u'CЕМЬ'
print x[:-1]  #prints CЕМ

【讨论】:

    【解决方案3】:
    x = u'some string'
    x2 = x[:-1]
    

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 2011-09-03
      • 2011-03-07
      • 1970-01-01
      • 2021-06-19
      相关资源
      最近更新 更多