将字符串拆分为不同长度的块 [英] Split the string into different lengths chunks

查看:69
本文介绍了将字符串拆分为不同长度的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了正确格式化字符串,我需要将其拆分为不同长度的块.

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

这篇关于将字符串拆分为不同长度的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆