删除utf-16(Python)上的非ascii字符

删除utf-16(Python)上的非ascii字符,python,Python,我有一些用于解密字符串的代码,字符串最初是加密的,来自.net源代码,但我能够使其正常工作。然而,进入python的字符串中有一些额外的字符,它必须解码为utf-16 下面是解密部分的一些代码。我加密的原始字符串是“test2”,这是我下面代码中文本变量中的内容 import Crypto.Cipher.AES import base64, sys password = base64.b64decode('PSCIQGfoZidjEuWtJAdn1JGYzKDonk9YblI0uv96O8s=

我有一些用于解密字符串的代码,字符串最初是加密的,来自.net源代码,但我能够使其正常工作。然而,进入python的字符串中有一些额外的字符,它必须解码为utf-16

下面是解密部分的一些代码。我加密的原始字符串是“test2”,这是我下面代码中文本变量中的内容

import Crypto.Cipher.AES
import base64, sys

password = base64.b64decode('PSCIQGfoZidjEuWtJAdn1JGYzKDonk9YblI0uv96O8s=') 
salt = base64.b64decode('ehjtnMiGhNhoxRuUzfBOXw==') 
aes = Crypto.Cipher.AES.new(password, Crypto.Cipher.AES.MODE_CBC, salt)
text = base64.b64decode('TzQaUOYQYM/Nq9f/pY6yaw==')

print(aes.decrypt(text).decode('utf-16'))
text1 = aes.decrypt(text).decode('utf-16')
print(text1)
我的问题是,当我解密并打印文本的结果时,它是“test2 europeu”,而不是预期的“test2”

如果我将相同的解密值保存到变量中,它会被错误解码为“틊첃陋ភ滑毾穬ヸ"

我的目标是我需要找到一种方法:

  • 从test2值的末尾去掉非ascii字符
  • 能够将其存储到包含正确字符串/文本值的变量中
  • 感谢您的帮助或建议?谢谢

    在python 2中,您可以使用
    str.decode
    ,如下所示:

    string.decode('ascii', 'ignore')
    
    区域设置为
    ascii
    ignore
    指定删除任何无法转换的内容

    在python 3中,由于默认情况下所有
    str
    对象都被解码为您的语言环境,因此在解码之前需要先对其重新编码:

    string.encode('ascii', 'ignore').decode()
    
    在python 2中,可以使用
    str.decode
    ,如下所示:

    string.decode('ascii', 'ignore')
    
    区域设置为
    ascii
    ignore
    指定删除任何无法转换的内容

    在python 3中,由于默认情况下所有
    str
    对象都被解码为您的语言环境,因此在解码之前需要先对其重新编码:

    string.encode('ascii', 'ignore').decode()
    

    Python2或3?.Python2或3?.awesome它修复了2个问题中的1个:)。我能够进行打印((aes.decrypt(text.decode('utf-16'))))。编码('ascii','ignore').decode())并且它摆脱了非ascii字符。但如果我将其保存到变量中,它将从作为Asain字符保存到只包含空字符串text1=(aes.decrypt)的变量(text).decode('utf-16')).encode('ascii','ignore').decode()@johnson类似这样:
    text1=aes.decrypt(text).decode('ascii',ignore')
    ok,所以我尝试了text1=aes.decrypt(text).decode('ascii',ignore'),结果是KNLZ0,而不是“test2”“@johnjohnson您是使用python 2还是python 3?也许您需要先转换为utf-16,然后再转换为ascii。好吧:)这是一段多么美妙的旅程啊。因此,现在这个功能非常好,text1=str(aes.decrypt(text),'utf-16')。encode('ascii','ignore')。decode('utf-8')。它修复了两个问题中的一个:)。我能够进行打印((aes.decrypt(text).decode('utf-16')).encode('ascii','ignore').decode()),它去掉了非ascii字符。但是如果我把它保存到一个变量中,它就从把它保存为Asain chars变为只包含空字符串text1=(aes.decrypt(text).decode('utf-16')).encode('ascii','ignore').decode()@johnjohnson类似这样的东西:
    text1=aes.decrypt(text).decode('ascii','ignore')
    ok,所以我尝试了text1=aes.decrypt(text.).decode)('ascii','ignore'),结果是KNLZ0,而不是“test2”@johnjohnson你是在python 2还是3上?也许你需要先转换为utf-16,然后再转换为ascii。好吧:)这是一个多么棒的旅程啊。所以现在这非常好用text1=str(aes.decrypt(text),'utf-16')。编码('ascii','ignore')。解码(“utf-8”)