简体   繁体   English

Python Hex-String - 每 x 个字符添加一个空格

[英]Python Hex-String - Add space every x characters

I have a string in python, that looks like this: str = '02001400ce01', which is in hex: 0x02, 0x00, 0x14, 0x00,0xce, 0x01.我在 python 中有一个字符串,看起来像这样:str = '02001400ce01',它是十六进制的:0x02、0x00、0x14、0x00、0xce、0x01。 I would like now to make the string to:我现在想将字符串设置为:

str = '02 00 14 00 ce 01' str = '02 00 14 00 ce 01'

How can I do this?我怎样才能做到这一点?

This code will work.此代码将起作用。


str = '02001400ce01'
offset = 0
for i in range(len(str)):
    if i % 2 == 1:
        offset += 1 
        #insert a space at position i
        str = str[:i+offset] + ' ' + str[i+offset:]
print(str)

You can do like this:你可以这样做:

string = '02001400ce01'
str_space = ' '.join(s1 + s2 for s1, s2 in zip(string[::2], string[1::2]))

Output:输出:

'02 00 14 00 ce 01'

您可以简单地使用maprange来生成字符串。

" ".join(list(map(lambda y: x[y:y+2],range(0,len(x),2))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM