如何解密字符串froom textbuffer.get_text

时间:2013-06-08 21:52:51

标签: python string gtk

我用pyDes编码一个char'a',我想解码它

   text = self.textbuffer.get_text(start, end)
   print text
   //',\xcc\x08\xe5\xa1\xa1fc'
   x = "{}".format(text)
   print x
   //',\xcc\x08\xe5\xa1\xa1fc'
but i need 
   //,塡fc

当我做的时候

cipher_text = ',\xcc\x08\xe5\xa1\xa1fc'
print cipher_text
//,塡fc

为什么

    text = self.textbuffer.get_text(start, end)
didn't return me a good string ? 

你的解决方案在这里不起作用,但我取得了进展:

text = self.textbuffer.get_text(start, end)
a = text.decode('unicode-escape')
g = a.encode('utf-16be')

这几乎是好的,但当我做的时候

print g
//',���fc'
print "%r"%g
//"\x00'\x00,\x00\xcc\x00\x08\x00\xe5\x00\xa1\x00\xa1\x00f\x00c\x00'"

现在我遇到了如何删除所有\ x00的问题

newstr = g.replace("\x00", "")
newstr2 = newstr.replace("'", "")

newstr2这是一个糟糕的解决方案,只适用于小字符串

2 个答案:

答案 0 :(得分:1)

你最好使用新的字符串格式化系统:

>>> cipher_text = ',\xcc\x08\xe5\xa1\xa1fc'
>>> print cipher_text
,塡fc
>>> print "%r" % cipher_text
',\xcc\x08\xe5\xa1\xa1fc'
>>> print "{}".format(cipher_text)
,塡fc
>>> p = "%r" % cipher_text
>>> print p
',\xcc\x08\xe5\xa1\xa1fc'
>>> p = "{}".format(cipher_text)
>>> print p
,塡fc

看起来格式化字符串的旧方法有严重的unicode vs ascii问题(这是我正在尝试解决的问题),而新的格式系统就像魅力一样。此外,它已准备好python3了!

  • 在向问题添加更多详细信息后进行编辑:

afaict,gtk使用unicode字符串没有问题。你应该从TextBuffer.get_text()中获取一个unicode字符串。所以为了确定我的假设,你应该先做:

print type(text) 

查看TextBuffer是否返回str()unicode()对象。

然后,您可以尝试

text = unicode(self.textbuffer.get_text(start, end)

text = self.textbuffer.get_text(start, end).encode('utf-8') 

甚至

text = '{}'.format(self.textbuffer.get_text(start_end))
在python中转换utf-8和ascii时,事情往往会变得棘手。关于这个主题有一本很好的手册,而且使用python3会有很多痛苦,python3默认使用unicode。 python2参考中有关于该主题的大文档:unicode howto

答案 1 :(得分:1)

你从textbuffer得到的是引用的字符串,这是因为你在把它放到那里之前引用它。如果在将字符串放入textbuffer之前引用该字符串:

self.textbuffer.set_text("%r" % k.encrypt(text))

然后你需要在检索它之后取消引用它:

import ast
text = ast.literal_eval(self.textbuffer.get_text(start, end))

这将为您提供您输入的原始字符串。

如果用户在文本视图中输入任意字符串,这很容易导致异常,或导致为text分配不正确类型的对象(例如数字)或名单。为避免这种情况,您可以在将文本放入缓冲区时删除引号,并使用codecs模块在​​两个方向上进行转义:

import codecs
self.text.buffer.set_text(codecs.encode(text, 'string-escape'))
...
text = codecs.decode(self.text.buffer.get_text(start, end), 'string-escape')