![](/img/trans.png)
[英]How do I convert unicode characters (ASCII 10) to text in Python
[英]Best way to Convert pairs of base 10 integers to ascii characters in python
我正在使用串行接口與一台測試設備進行交談。 設備的兩個字母的ascii ID在特定寄存器中被編碼為以10為基的整數。 每對整數都需要轉換為ASCII字符。 我的問題是進行此轉換的最佳方法是什么。 我使用了下面的方法,但是對於這樣一個簡單的任務來說,它似乎相當復雜。
例
輸入: 5270
所需的輸出: '4F'
(ascii值52和70)
get the raw register value
>>> result =f4.read_register(0,)
>>> result
5270
convert the integer into a list of chars
>>> chars = [i for i in str(result)]
join the pairs together
>>> pairs = [''.join((chars[x], chars[x+1])) for x in xrange(0,len(chars),2)]
>>> pairs
['52', '70']
>>> pairs = [chr(int(x)) for x in pairs]
>>> pairs
['4', 'F']
除了@BhargavRao答案,您還可以使用divmod
內置:
num = 5270
''.join(map(chr, divmod(num, 100)))
# '4F'
您還可以使用字符串格式:
'{:c}{:c}'.format(*divmod(num, 100))
# '4F'
添加一些數學。
/
-整數除法 %
-模運算符 碼
>>> num = 5270
>>> pairs = [chr(num/100),chr(num%100)]
>>> pairs
['4', 'F']
並匹配所需的輸出
>>> ''.join(pairs)
'4F'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.