![](/img/trans.png)
[英]“01”-string representing bytes to unicode conversion in python 2
[英]Unicode, Bytes, and String to Integer Conversion
我正在編寫一個程序來處理外國字母表中的字母。 該程序正在輸入一個與字符的 unicode 數字相關聯的數字。 例如 062A 是在 unicode 中為該字符分配的編號。
我首先要求用戶輸入與特定字母相對應的數字,即 062A。 我現在試圖將該數字轉換為一個 16 位整數,該整數可以由 python 解碼以將字符打印回用戶。
例子:
打印(字節([0x94,0x03])。解碼('utf-16'))
但是當我使用
int('062A', '16')
我收到此錯誤:
ValueError:int() 的無效文字,基數為 10:'062A'
我知道這是因為我在字符串中使用了 A,但這是符號的 unicode。 誰能幫我?
但是,當我使用
int('062A', '16')
,我收到此錯誤:ValueError: invalid literal for int() with base 10: '062A'
不,你不是:
>>> int('062A', '16')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
正如它所說的那樣。 問題不是'062A'
,而是'16'
。 基數應直接指定為整數,而不是字符串:
>>> int('062A', 16)
1578
如果要得到對應編號的Unicode碼位,那么通過bytes和UTF-16進行轉換,工作量太大了。 直接使用chr
詢問即可,例如:
>>> chr(int('0394', 16))
'Δ'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.