簡體   English   中英

使用轉義字符'\\ x'創建字符串並在python中輸入用戶

[英]Create a string with escape characters '\x' and user input in python

我試圖用用戶輸入的'\\ x'轉義字符創建一個字符串

我正在做這樣的事情-

    def create_hex_string(a, b): # a and b are integers of range (0-255)
        # convert decimal to hex and pad it with 0
        # for eg: 10 -> 0x0a
        ahex = "{0:#0{1}x}".format(register,4)
        bhex = "{0:#0{1}x}".format(value,4)
        str = "\x08\x{}\x00\x{}".format(ahex[2:], bhex[2:])
        return str

當我嘗試執行此操作時,轉義字符不再相關,這給了我一個錯誤。

我還嘗試使用文字字符串通過用戶輸入來創建十六進制字符串,例如-

str = r'\x08\x{}\x00\x{}'.format(ahex[2:], bhex[2:])

但是我找不到一種將文字字符串轉換回可以識別轉義字符的非文字字符串的方法。

我還嘗試查看re.escape()的工作方式,但是它轉義了除ASCII之外的所有字符。 任何有關此的指針將不勝感激。


更好的解釋

我有一個帶寄存器的外圍硬件設備。 我可以通過套接字在設備的特定寄存器中設置特定值。

sock.send("\x80\x01")

該命令僅在用雙引號引起來的字符串時才有效,因此\\ x轉義符具有含義。 上面的命令會將寄存器128設置為值1,因為-0x80 = 128 0x01 = 1

根據這種思路,我創建了一個函數

1   def create_hex_string(register, value): # a and b are integers of range (0-255)
2       # funky stuff to convert register and value to hex.
3       # reghex = hex value of register (128 = 80 in hex)
4       # valhex = hex value of value (1 = 01 in hex)
5       str = "\x{}\x{}".format(reghex, valhex)
6   return str

7   cmd = create_hex_string(128, 1)
8   sock.send(cmd)

如果看到的話,第5行會給出錯誤,它不會接受。 而不是在第7行中用雙引號引起來的字符串,我使用了帶格式的文字字符串。

5    str = r'\x{}\x{}'.format(reghex, valhex)

這樣我就失去了轉義字符的意義。

我希望這有助於更好地理解問題。 如果我錯過了什么,請允許我,我將在下一次編輯中添加它。

您可以使用chr()函數從整數值創建一個單字符字符串。

這是您要做什么?

def create_hex_string(a, b): # a and b are integers of range (0-255)
    return "\x08{}\x00{}".format(chr(a), chr(b))

s = create_hex_string(65, 66)
assert s[0] == '\x08'
assert s[1] == 'A'
assert s[2] == '\x00'
assert s[3] == 'B'
assert s == "\x08\x41\x00\x42"

# The example from OP's comment:
assert create_hex_string(128, 1) == "\x08\x80\x00\x01"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM