每隔第n个字符拆分字符串?

Bra*_*ett 342 python string split

是否有可能每隔第n个字符拆分一个python字符串?

例如,假设我有一个包含以下内容的字符串:

'1234567890'
Run Code Online (Sandbox Code Playgroud)

我怎么能让它看起来像这样:

['12','34','56','78','90']
Run Code Online (Sandbox Code Playgroud)

sat*_*oto 503

>>> line = '1234567890'
>>> n = 2
>>> [line[i:i+n] for i in range(0, len(line), n)]
['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)

  • 这是一个非常好的答案,因为它不会以任何方式进行复杂化,而且这一事实使您可以轻松地记住该方法,因为它非常简单 (25认同)
  • 具有讽刺意味的是,试图以一种不具有隐藏意义的方式使用单词,往往会导致错综复杂的句子. (5认同)
  • 非常适合分解长行以进行打印,例如“for i in range(0, len(string), n): print(string[i:i+n])” (4认同)
  • 我是认真的,我在模拟器的二进制转换器中使用了这段代码,我喜欢它是一个 pythonic for 循环哈哈,但感谢进一步分解我喜欢这个方法的原因! (2认同)
  • 对于像我这样没有列表推导式的菜鸟来说,以下内容可能更容易理解,代替最后一行: `substrings = []` `for i in range(0, len(line), n): substring = line[i:i+n] substrings.append(substring)` (2认同)

the*_*olf 187

为了完成,您可以使用正则表达式执行此操作:

>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)

正如评论中指出的那样,你可以这样做:

>>> import re
>>> re.findall('..?', '123456789')
['12', '34', '56', '78', '9']
Run Code Online (Sandbox Code Playgroud)

您还可以执行以下操作,以简化较长块的正则表达式:

>>> import re
>>> re.findall('.{1,2}', '123456789')
['12', '34', '56', '78', '9']
Run Code Online (Sandbox Code Playgroud)

re.finditer如果字符串很长,你可以使用chunk来生成chunk.

  • 这是迄今为止最好的答案,值得在上面。甚至可以写成 `'.'*n` 以使其更清楚。没有连接,没有压缩,没有循环,没有列表理解;只需找到彼此相邻的下两个字符,这正是人类大脑的思考方式。如果巨蟒还活着,他会喜欢这种方法的! (8认同)
  • 如果字符串包含换行符,这将不起作用。这需要`flags=re.S`。 (6认同)
  • 对于相当长的字符串来说,这也是最快的方法:https://gitlab.com/snippets/1908857 (2认同)

Dip*_*ami 114

为此,python中已经有一个内置函数.

>>> from textwrap import wrap
>>> s = '1234567890'
>>> wrap(s, 2)
['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)

这就是包装的docstring所说的:

>>> help(wrap)
'''
Help on function wrap in module textwrap:

wrap(text, width=70, **kwargs)
    Wrap a single paragraph of text, returning a list of wrapped lines.

    Reformat the single paragraph in 'text' so it fits in lines of no
    more than 'width' columns, and return a list of wrapped lines.  By
    default, tabs in 'text' are expanded with string.expandtabs(), and
    all other whitespace characters (including newline) are converted to
    space.  See TextWrapper class for available keyword args to customize
    wrapping behaviour.
'''
Run Code Online (Sandbox Code Playgroud)

  • 这确实回答了这个问题,但是如果有空格并且您希望将它们保留在拆分字符中,会发生什么情况?wrap()删除空格(如果空格在一组字符分割后立即掉落) (3认同)
  • print(wrap('12345678',3))将字符串分成3位数字的组,但是从前面开始而不是从后面开始。结果:['123','456','78'] (2认同)
  • 了解“包装”很有趣,但它并没有完全按照上面的要求进行。它更倾向于显示文本,而不是将字符串拆分为固定数量的字符。 (2认同)
  • 如果字符串包含空格,`wrap`可能不会返回要求的内容。例如`wrap('0 1 2 3 4 5',2)`返回`['0','1','2','3','4','5']`(元素被剥离) (2认同)
  • 如果您想用连字符分割文本(您作为参数给出的数字实际上是最大字符数,而不是精确的字符数,并且它会在连字符和空格上中断),那么这种方法效果很差。 (2认同)

And*_*ark 76

将元素分组为n长度组的另一种常用方法:

>>> s = '1234567890'
>>> map(''.join, zip(*[iter(s)]*2))
['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)

这个方法直接来自docs zip().

  • 如果有人发现`zip(*[iter(s)]*2)'难以理解,请阅读[zip(*[iter(s)]*n)如何在Python中工作?](http:// stackoverflow .COM /问题/ 2233204 /如何此结果zipitersn-工作中的Python). (15认同)
  • 这不会占到奇数个字符,它只会丢弃这些字符:`>>> map(''.join,zip(*[iter('01234567')]*5))` - >`[ '01234']` (13认同)
  • 要处理奇数个字符,只需将`zip()`替换为`itertools.zip_longest()`:`map(''.join,zip_longest(*[iter(s)]*2,fillvalue =''))` (3认同)
  • 在[19]中:a ="你好世界"; list(map("".join,zip(*[iter(a)]*4)))得到结果['hell','o wo']. (2认同)

Rus*_*ove 53

我认为这比itertools版本更短,更易读:

def split_by_n(seq, n):
    '''A generator to divide a sequence into chunks of n units.'''
    while seq:
        yield seq[:n]
        seq = seq[n:]

print(list(split_by_n('1234567890', 2)))
Run Code Online (Sandbox Code Playgroud)

  • 但效率不高:当应用于字符串时:副本太多 (5认同)

vlk*_*vlk 23

我喜欢这个解决方案:

s = '1234567890'
o = []
while s:
    o.append(s[:2])
    s = s[2:]
Run Code Online (Sandbox Code Playgroud)


tim*_*els 22

使用PyPI中的more-itertools:

>>> from more_itertools import sliced
>>> list(sliced('1234567890', 2))
['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)


Eug*_*ash 10

您可以使用以下grouper()配方itertools:

Python 2.x:

from itertools import izip_longest    

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)

Python 3.x:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
Run Code Online (Sandbox Code Playgroud)

这些函数具有内存效率,适用于任何迭代.


Str*_*ick 9

我被困在同一个场景中。

这对我有用

x="1234567890"
n=2
list=[]
for i in range(0,len(x),n):
    list.append(x[i:i+n])
print(list)
Run Code Online (Sandbox Code Playgroud)

输出

['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)


end*_*ill 8

试试下面的代码:

from itertools import islice

def split_every(n, iterable):
    i = iter(iterable)
    piece = list(islice(i, n))
    while piece:
        yield piece
        piece = list(islice(i, n))

s = '1234567890'
print list(split_every(2, list(s)))
Run Code Online (Sandbox Code Playgroud)


小智 7

这可以通过一个简单的 for 循环来实现。

a = '1234567890a'
result = []

for i in range(0, len(a), 2):
    result.append(a[i : i + 2])
print(result)
Run Code Online (Sandbox Code Playgroud)

输出看起来像 ['12', '34', '56', '78', '90', 'a']

  • 这与此处的解决方案相同:/sf/answers/4136405521/ (4认同)
  • 虽然此代码可以回答问题,但提供有关此代码为何和/或如何回答问题的附加上下文可以提高其长期价值。 (3认同)

ben*_*n w 6

>>> from functools import reduce
>>> from operator import add
>>> from itertools import izip
>>> x = iter('1234567890')
>>> [reduce(add, tup) for tup in izip(x, x)]
['12', '34', '56', '78', '90']
>>> x = iter('1234567890')
>>> [reduce(add, tup) for tup in izip(x, x, x)]
['123', '456', '789']
Run Code Online (Sandbox Code Playgroud)


Sqr*_*ter 5

一如既往,对于那些喜欢单衬的人

n = 2  
line = "this is a line split into n characters"  
line = [line[i * n:i * n+n] for i,blah in enumerate(line[::n])]
Run Code Online (Sandbox Code Playgroud)


U10*_*ard 5

试试这个:

s='1234567890'
print([s[idx:idx+2] for idx,val in enumerate(s) if idx%2 == 0])
Run Code Online (Sandbox Code Playgroud)

输出:

['12', '34', '56', '78', '90']
Run Code Online (Sandbox Code Playgroud)