1. 程式人生 > >Python3小程式:把字串轉換成連續的UTF8編碼(16位)

Python3小程式:把字串轉換成連續的UTF8編碼(16位)

# coding: utf-8
import binascii
'''
參考程式碼1
mystery = b"\xe5\x88\xab"
x = mystery.decode('utf-8')
print(x)


y = bytearray.fromhex(\xe5\x88\xab).decode()
print(y)
'''

'''
參考程式碼2
var = 1
while var == 1:
    a = str(input('請輸入字串:\n'))
    b = []
    for i in a:
        c = hex(ord(i))
        print(c)

#    print('轉換結果為:\n\n\n{}\n\n'.format(x))
'''

'''
參考程式碼3
x = '\x53\x21\x6a'  
y = [eval(hex(ord(c))) for c in x]
print(y)
k = bytearray(y)
z = binascii.b2a_hex(k)
print(z)
'''


var = 1
while var == 1:
    a = str(input('請輸入字串:\n'))
    b = []
    for i in a:
        c = i.encode('utf8')
        #print(c)
        y = [eval(hex(j)) for j in c]
        #print(y)
        k = bytearray(y)
        z = str(binascii.b2a_hex(k))
        #print(z)
        z = z.replace('b','',1)
        #print(z)
        b.append(eval(z))
        #print (b)
    p = ''.join(b)
    print('轉換結果為:\n\n{}\n'.format(p))





例:

輸入:呵呵[email protected]#

輸出:e591b5e591b5313233616263214023