如何构造一个要读取为unicode的字符串?

时间:2017-03-31 15:09:50

标签: python python-2.7 unicode

我正在尝试将4位二进制字符串转换为十六进制数字(0-f),然后将其中几个数字组合成一个Unicode字符串,然后将其打印为单个ASCII字符。这要求我在每个Unicode字符的开头都有“\”,但是尝试将十六进制数字添加到“\”会在扫描字符串文字时返回“SyntaxError:EOL。”

将它们添加到“\\”可以避免错误,但是现在形成的Unicode字符串将打印为“\ XXX”而不是单个字符。

打印“\ x3f”返回? print“\ x3f”返回\ x3f

有没有办法通过附加到字符串来动态构造Unicode字符串?

2 个答案:

答案 0 :(得分:2)

您的输入和输出应该是什么样子并不容易理解,但这些功能应该可以帮助您实现目标:

>>> "1010"
'1010'
>>> int("1010",2)
10
>>> hex(int("1010",2))
'0xa'
>>> hex(int("1010",2))[2:]
'a'
>>> hex1 = hex(int("1010",2))[2:]
>>> hex2 = hex(int("0101",2))[2:]
>>> hex1+hex2
'a5'
>>> int(hex1+hex2,16)
165
>>> int("1010"+"0101",2)
165
>>> unichr(int(hex1+hex2,16))
u'\xa5'

答案 1 :(得分:0)

如果没有输入和输出示例,我可以提出以下内容:

sample_string = u'\xa1There is no \xa2\u014fw level!'

# nibbles = [i for s in [[y[0:4], y[4:]] for y in ['{:08b}'.format(x) for x in map(ord, list(sample_string.encode('utf-8')))]] for i in s]

nibbles = [
    '1100', '0010', '1010', '0001', '0101', '0100', '0110', '1000',
    '0110', '0101', '0111', '0010', '0110', '0101', '0010', '0000',
    '0110', '1001', '0111', '0011', '0010', '0000', '0110', '1110',
    '0110', '1111', '0010', '0000', '1100', '0010', '1010', '0010',
    '1100', '0101', '1000', '1111', '0111', '0111', '0010', '0000',
    '0110', '1100', '0110', '0101', '0111', '0110', '0110', '0101',
    '0110', '1100', '0010', '0001'
]

# Make the list of nibbles (4 bits) into a list of bytes (8 bits)
bytelist = [ x[0] + x[1] for x in zip(nibbles[0::2], nibbles[1::2])]

# Make sure the bytelist is half the size of the nibble list:
len(nibbles) == len(bytelist) * 2
# True

# Change each byte in the bytelist into UTF-8 hex codes
hexlist = ['0x{:02x}'.format(int(y, 2)) for y in bytelist]

# create a list of integers from hex string values
intlist = [int(x, 0) for x in hexlist]

# Print it out!
print(''.join(chr(x) for x in intlist))

# Or, you can convert it into unicode:
unistr = unicode(''.join(chr(x) for x in intlist), 'utf-8')
print(unistr)

修订

在jsbueno的评论之后,我想我看到OP正在尝试做什么。处理多字节unicode似乎很难。让我们在字符串中抛出一个多字节字符:

def decodeNibbles(nibbles):
    if len(nibbles) % 2 != 0:
        raise ValueError('Uneven number of nibbles given')
    unistr = ''.join(
            chr(int('{:s}'.format(y), 2))
            for y in [ x[0] + x[1] for x in zip(nibbles[0::2], nibbles[1::2])]
        )
    return unistr

nibbles = [
    '1100', '0010', '1010', '0001', '0101', '0100', '0110', '1000',
    '0110', '0101', '0111', '0010', '0110', '0101', '0010', '0000',
    '0110', '1001', '0111', '0011', '0010', '0000', '0110', '1110',
    '0110', '1111', '0010', '0000', '1100', '0010', '1010', '0010',
    '1100', '0101', '1000', '1111', '0111', '0111', '0010', '0000',
    '0110', '1100', '0110', '0101', '0111', '0110', '0110', '0101',
    '0110', '1100', '0010', '0001'
]

decodedString = decodeNibbles(nibbles)
print(decodedString)
# ¡There is no ¢ŏw level!

所有这些都可以压缩到以下内容:

extension UIImage {

    func changeTintColor(color: UIColor) -> UIImage {
        var newImage = self.withRenderingMode(.alwaysTemplate)
        UIGraphicsBeginImageContextWithOptions(self.size, false, newImage.scale)
        color.set()
        newImage.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
        newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }

    func changeColor(color: UIColor) -> UIImage {
        let backgroundSize = self.size
        UIGraphicsBeginImageContext(backgroundSize)
        guard let context = UIGraphicsGetCurrentContext() else {
            return self
        }
        var backgroundRect = CGRect()
        backgroundRect.size = backgroundSize
        backgroundRect.origin.x = 0
        backgroundRect.origin.y = 0

        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        context.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
        context.translateBy(x: 0, y: backgroundSize.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.clip(to: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height),
                 mask: self.cgImage!)
        context.fill(backgroundRect)

        var imageRect = CGRect()
        imageRect.size = self.size
        imageRect.origin.x = (backgroundSize.width - self.size.width) / 2
        imageRect.origin.y = (backgroundSize.height - self.size.height) / 2

        context.setBlendMode(.multiply)
        context.draw(self.cgImage!, in: imageRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }

}