我正在使用 pyserial 并且需要发送一些小于 255 的值。如果我发送 int 本身,则会发送 int 的 ascii 值。所以现在我将 int 转换为 unicode 值并通过串口发送它。
unichr(numlessthan255);
However it throws this error:
'ascii' codec can't encode character u'\x9a' in position 24: ordinal not in range(128)
将 int 转换为 unicode 的最佳方法是什么?
最佳答案
在 Python 2 中 - 先将其转换为字符串,然后再转换为 unicode。
str(integer).decode("utf-8")
我认为的最佳方式。适用于任何整数,如果您将字符串作为输入,则仍然有效。
由于评论而更新编辑:对于 Python 2 和 3 - 这适用于两者但有点困惑:
str(integer).encode("utf-8").decode("utf-8")
关于python - 将 int 值转换为 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17627834/