Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into different lengthed chunks?

Tags:

python

string

In order to format the string properly, I was required to split it into different lengths of chunks.

As an example, This is a string - "25c319f75e3fbed5a9f0497750ea12992b30d565", For splitting it in fixed length chunks, I would simply use steps and slicing:

s = '25c319f75e3fbed5a9f0497750ea12992b30d565'
n = 2
print("-".join([s[i:i+n] for i in range(0, len(s), n)]))

However, What could I do if n was a list of numbers to be split, as example:

s = '25c319f75e3fbed5a9f0497750ea12992b30d565'
n = [8, 4, 4, 4, 4, 12]

Only solution I made was this:

print("-".join([s[0:8], s[8:12], s[12:16], s[16:20], s[20:24], s[24:32]]))

Which is not "pythonic" and more necessarily not reliable if the length of the string is large.

The output from the last example of code:

25c319f7-5e3f-bed5-a9f0-4977-50ea1299

So can this be done in a more pythonic one liner way? If not, what are other more automatic ways for this to be done?

like image 977
ShellRox Avatar asked Dec 06 '25 18:12

ShellRox


1 Answers

>>> s = '25c319f75e3fbed5a9f0497750ea12992b30d565'
>>> n = [8, 4, 4, 4, 4, 12]
>>> print '-'.join([s[sum(n[:i]):sum(n[:i+1])] for i in range(len(n))])

Output

25c319f7-5e3f-bed5-a9f0-4977-50ea12992b30
like image 81
cs95 Avatar answered Dec 08 '25 10:12

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!