Reputation:
I have a string of a fixed length.
>>> s = "000000000001048700000010768"
I need to split this string into parts of 5 characters in reversed order (starting from last character). The output should be:
00 00000 00001 04870 00000 10768
I found the textwrap
module, which does the splitting, But the output is slightly different.
>>> import textwrap
>>> print ' '.join(textwrap.wrap(s, 5))
00000 00000 01048 70000 00107 68
Is there an easy solution to do this that I am missing? Maybe to use s.format()
Upvotes: 1
Views: 137
Reputation: 3786
Reverse the string before you split it.
parts = textwrap.wrap(s[::-1], 5)
Then you can reverse the list, to go back to the original order.
print " ".join(parts[::-1])
Or in short:
print " ".join(textwrap.wrap(s[::-1], 5)[::-1])
Upvotes: 2
Reputation: 28606
A regex way, now that you confirmed that you don't actually want to split but just add spaces.
>>> import re
>>> re.sub('(.{5})(?=.)', r'\1 ', s[::-1])[::-1]
'00 00000 00001 04870 00000 10768'
This grabs five chars followed by something (I wish \z
would work) and replaces them with themselves plus a space. Reversing the input string beforehand and the output string afterwards in order to do the right-to-left grouping.
Upvotes: 0
Reputation: 73470
Solution without textwrap and reversing the string twice:
print ' '.join(s[max(i-5, 0):i] for i in reversed(range(len(s), 0, -5)))
Upvotes: 0