为了正确格式化字符串,我需要将其拆分为不同长度的块.
In order to format the string properly, I was required to split it into different lengths of chunks.
作为一个例子,这是一个字符串-25c319f75e3fbed5a9f0497750ea12992b30d565,为了将其拆分为固定长度的块,我将仅使用步骤和切片:
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)]))但是,如果n是要拆分的数字列表,我该怎么办,例如:
However, What could i do if n was list of numbers to be split, As example:
s = '25c319f75e3fbed5a9f0497750ea12992b30d565' n = [8, 4, 4, 4, 4, 12] # edited for consistency - Coldspeed我唯一的解决方法是:
print("-".join([s[0:8], s[8:12], s[12:16], s[16:20], s[20:24], s[24:32]]))不是pythonic的,更不可靠的字符串长度很大.
Which is not pythonic and more necessarily not reliable length of string is large.
最后一个代码示例的输出:
The output from the last example of code:
25c319f7-5e3f-bed5-a9f0-4977-50ea1299那么这可以用更pythonic的一种衬里方式完成吗?如果不是,还有什么其他更自动的方法可以完成?
So can this be done in more pythonic one liner way? If not what are other more automatic ways for this to be done?
推荐答案>>> 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))])
输出
25c319f7-5e3f-bed5-a9f0-4977-50ea12992b30更多推荐
将字符串拆分为不同长度的块
发布评论