Reputation:
I have a string for example:
"112233445566778899"
How can I spilt it to the following pattern:
"\x11\x22\x33\x44\x55\x66\x77\x88\x99"
I could spilt the string with following commands, but I could find out a way to append "\x" to the them:
s = "112233445566778899"
[s[i:i + 2] for i in range(0, len(s), 2)]
Upvotes: 0
Views: 147
Reputation: 1399
I think using regular expressions can you the best. Because it can find doubled characters anywhere on the string.
>>>import re
>>>string = "112233445566778899"
>>>x = ''.join(r'\x{}'.format(s) for s in re.finditer(r'(\w)\1',string))
>>>x
'\\x11\\x22\\x33\\x44\\x55\\x66\\x77\\x88\\x99'
>>> print(x)
\x11\x22\x33\x44\x55\x66\x77\x88\x99
Upvotes: 0
Reputation: 459
s = "112233445566778899"
a = [r'\x' + s[i:i + 2] for i in range(0, len(s), 2)]
print(''.join(a))
Upvotes: 0
Reputation: 22953
Assuming your string will always have an even length, you always want to split the string into pairs, and that your string is already ordered:
>>> string = "112233445566778899"
>>> joined = ''.join(r'\x{}'.format(s + s) for s in string[1::2])
>>> print(joined)
\x11\x22\x33\x44\x55\x66\x77\x88\x99
>>>
Upvotes: 1
Reputation: 6723
You can do the following edit to your code:
...
[r"\x"+s[i:i + 2] for i in range(0, len(s), 2)]
...
Notice that this will return two forward slashes:
['\\x11', '\\x22', '\\x33', '\\x44', '\\x55', '\\x66', '\\x77', '\\x88', '\\x99']
This is because of Python escaping the \
using the escaping character \
.
When using the string you will notice that one of the \
disappears:
>> x = ['\\x11', '\\x22', '\\x33', '\\x44', '\\x55', '\\x66', '\\x77', '\\x88', '\\x99']
>> print(x[0])
>> '\x11'
Upvotes: 0