python - 将 int 值转换为 unicode

标签 python character-encoding ascii pyserial

我正在使用 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/

相关文章:

arrays - 为什么我的矩阵值在 C 中消失了?

python - keras model.fit_generator() 比 model.fit() 慢几倍

python 脚本参数在 Hudson Execute Shell 步骤中被误解

java - Android 和 Oracle Java 的字符串字符编码

python - 通过python代码从mysql读取时对编码问题感到困惑

java - 整数循环到希腊字符 - Java

java - 将小写字母递减为仅小写字母

python - 条件类创建 (Python)

python - 将我自己的描述属性添加到 Pandas DataFrame

php - 字符在 mysql 中显示为乱码(希伯来语)