将字符串拆分为不同长度的块

编程入门 行业动态 更新时间:2024-10-13 08:23:34
本文介绍了将字符串拆分为不同长度的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

将字符串拆分为不同长度的块

本文发布于:2023-11-29 22:28:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   长度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!