简体   繁体   English

将字符串分成一定长度的较小字符串列表

[英]Dividing a string into a list of smaller strings of certain length

If i have this string: 如果我有这个字符串:

"0110100001100101011011000110110001101111"

How can I divide it at every eighth character into smaller strings, and put it into a list, so that it looks like this?: 如何将每八个字符分成较小的字符串,并将其放入一个列表中,以便它看起来像这样?:

['01101000','01100101','01101100','01101100','01101111']

So far, I can't figure out how this would be possible. 到目前为止,我无法弄清楚这是怎么可能的。

I should mention, since my strings are in binary so the length is always a multiple of 8. 我应该提一下,因为我的字符串是二进制的,所以长度总是8的倍数。

>>> mystr = "0110100001100101011011000110110001101111"
>>> [mystr[i:i+8] for i in range(0, len(mystr), 8)]
['01101000', '01100101', '01101100', '01101100', '01101111']

The solution uses a so called list comprehension ( this seems to be a pretty decent tutorial) and is doing basically the same as Aleph's answer, just in one line. 该解决方案使用所谓的列表理解( 似乎是一个相当不错的教程),并且基本上与Aleph的答案相同,只是在一行中。

t=[]
for i in range(len(yourstring)/8):
    t.append(yourstring[i*8: (i+1)*8])

You can also use re 你也可以使用re

import re

In [21]: s="0110100001100101011011000110110001101111"

In [22]: re.findall('.{8}',s)
Out[22]: ['01101000', '01100101', '01101100', '01101100', '01101111']

As your strings only contain digits we can use . 由于您的字符串只包含我们可以使用的数字. to match any character. 匹配任何角色。

You can also explicitly use the \\d{8} which matches 8 digits in a low. 您还可以明确使用匹配8位数的\\d{8}

In [23]: In [22]: re.findall('\d{8}',s)
Out[23]: ['01101000', '01100101', '01101100', '01101100', '01101111']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM