所以我有这样的事情:
x = "CЕМЬ"
x[:len(x)-1]
从字符串中删除最后一个字符。 但它不起作用,它给了我一个错误。我认为这是因为它是Unicode。那么如何在非ansi字符串上进行这种简单的格式化呢。
答案 0 :(得分:6)
那是因为在Python 2.x "CЕМЬ"
中,编写字节字符串b'C\xd0\x95\xd0\x9c\xd0\xac'
是一种奇怪的方式。
您需要字符字符串。在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 -*-
答案 1 :(得分:1)
使用utf-8
编码保存文件:
# -*- coding: utf-8 -*-
x = u'CЕМЬ'
print x[:-1] #prints CЕМ
答案 2 :(得分:0)
x = u'some string'
x2 = x[:-1]