Python 每N个字符拆分一个字符串?

Python 每N个字符拆分一个字符串?,python,string,split,Python,String,Split,是否可以每N个字符拆分一个字符串 例如,假设我有一个包含以下内容的字符串: '1234567890' 我怎样才能让它看起来像这样: ['12','34','56','78','90'] 请尝试以下代码: from itertools import islice def split_every(n, iterable): i = iter(iterable) piece = list(islice(i, n)) while piece: yield p

是否可以每N个字符拆分一个字符串

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

'1234567890'
我怎样才能让它看起来像这样:

['12','34','56','78','90']

请尝试以下代码:

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)))

请尝试以下代码:

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)))

我认为这比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)))

我认为这比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)))

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

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

此方法直接来自文档。

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

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

此方法直接来自的文档。

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

>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']
对于奇数个字符,可以执行以下操作:

>>> import re
>>> re.findall('..?', '123456789')
['12', '34', '56', '78', '9']
您还可以执行以下操作,以简化更长块的正则表达式:

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

如果字符串很长,可以使用
re.finditer
逐块生成

为了完整起见,您可以使用正则表达式:

>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']
对于奇数个字符,可以执行以下操作:

>>> import re
>>> re.findall('..?', '123456789')
['12', '34', '56', '78', '9']
您还可以执行以下操作,以简化更长块的正则表达式:

>>> import re
>>> re.findall('.{1,2}', '123456789')
['12', '34', '56', '78', '9']
如果字符串很长,可以使用
re.finditer
逐块生成

我喜欢这个解决方案:

s = '1234567890'
o = []
while s:
    o.append(s[:2])
    s = s[2:]
我喜欢这个解决方案:

s = '1234567890'
o = []
while s:
    o.append(s[:2])
    s = s[2:]

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


这些函数具有内存效率,可与任何iterables一起使用。

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


这些函数的内存效率很高,可以与任何iterables一起使用。

对于那些喜欢一行程序的人来说,一如既往

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])]

和往常一样,对于那些喜欢一句台词的人

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])]
从PyPI中使用:

>>> from more_itertools import sliced
>>> list(sliced('1234567890', 2))
['12', '34', '56', '78', '90']
从PyPI中使用:

>>> from more_itertools import sliced
>>> list(sliced('1234567890', 2))
['12', '34', '56', '78', '90']
以前有过。以下是库中的四个选项:

s = "1234567890"

["".join(c) for c in mit.grouper(2, s)]

["".join(c) for c in mit.chunked(s, 2)]

["".join(c) for c in mit.windowed(s, 2, step=2)]

["".join(c) for c in  mit.split_after(s, lambda x: int(x) % 2 == 0)]
后面的每个选项都会产生以下输出:

['12', '34', '56', '78', '90']
所讨论选项的文档:,

以前已提供。以下是库中的四个选项:

s = "1234567890"

["".join(c) for c in mit.grouper(2, s)]

["".join(c) for c in mit.chunked(s, 2)]

["".join(c) for c in mit.windowed(s, 2, step=2)]

["".join(c) for c in  mit.split_after(s, lambda x: int(x) % 2 == 0)]
后面的每个选项都会产生以下输出:

['12', '34', '56', '78', '90']

所讨论选项的文档:,

python中已经有一个内置函数用于此操作

>>> from textwrap import wrap
>>> s = '1234567890'
>>> wrap(s, 2)
['12', '34', '56', '78', '90']
这是wrap的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.
'''

python中已经有一个内置函数用于此

>>> from textwrap import wrap
>>> s = '1234567890'
>>> wrap(s, 2)
['12', '34', '56', '78', '90']
这是wrap的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.
'''
试试这个:

s='1234567890'
print([s[idx:idx+2] for idx,val in enumerate(s) if idx%2 == 0])
输出:

['12', '34', '56', '78', '90']
试试这个:

s='1234567890'
print([s[idx:idx+2] for idx,val in enumerate(s) if idx%2 == 0])
输出:

['12', '34', '56', '78', '90']

短字符串的简单递归解决方案:

def split(s, n):
    if len(s) < n:
        return []
    else:
        return [s[:n]] + split(s[n:], n)

print(split('1234567890', 2))
def拆分(s,n):
如果len(s)
或以这种形式:

def split(s, n):
    if len(s) < n:
        return []
    elif len(s) == n:
        return [s]
    else:
        return split(s[:n], n) + split(s[n:], n)
def拆分(s,n):
如果len(s)

,它更明确地说明了递归方法中的典型分治模式(尽管实际上没有必要这样做)

一个简单的短字符串递归解决方案:

def split(s, n):
    if len(s) < n:
        return []
    else:
        return [s[:n]] + split(s[n:], n)

print(split('1234567890', 2))
def拆分(s,n):
如果len(s)
或以这种形式:

def split(s, n):
    if len(s) < n:
        return []
    elif len(s) == n:
        return [s]
    else:
        return split(s[:n], n) + split(s[n:], n)
def拆分(s,n):
如果len(s)

,它更明确地说明了递归方法中典型的分而治之模式(尽管实际上没有必要这样做)

我也遇到了同样的问题

这对我有用

x="1234567890"
n=2
list=[]
for i in range(0,len(x),n):
    list.append(x[i:i+n])
print(list)
输出

['12', '34', '56', '78', '90']

我被困在同一个场景中

这对我有用

x="1234567890"
n=2
list=[]
for i in range(0,len(x),n):
    list.append(x[i:i+n])
print(list)
输出

['12', '34', '56', '78', '90']

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

a = '1234567890a'
result = []

for i in range(0, len(a), 2):
    result.append(a[i : i + 2])
print(result)
输出看起来像
这可以通过一个简单的for循环来实现

a = '1234567890a'
result = []

for i in range(0, len(a), 2):
    result.append(a[i : i + 2])
print(result)
输出看起来像
[19]:a=“你好,世界”中的[12]、[34]、[56]、[78]、[90]、[a']

;列表(map(“.join,zip(*[iter(a)]*4)))获取结果['hell','o wo']。如果有人发现
zip(*[iter(s)]*2
很难理解和阅读。这并不能解释奇数个字符,只需删除这些字符:
>map('.join,zip(*[iter('01234567')]]*5))
->
['01234']
若要处理奇数字符,只需将
zip()
替换为
itertools.zip_longest()
map(''.join,zip_longest(*[iter(s)]*2,fillvalue='')
也很有用:文档用于[19]:a=“hello world”;列表(map(“.join,zip(*[iter(a)]*4)))获取结果['hell','o wo']。如果有人发现
zip(*[iter(s)]*2
很难理解和阅读。这并不能解释奇数个字符,只需删除这些字符:
>map('.join,zip(*[iter('01234567')]]*5))
->
['01234']
若要处理奇数字符,只需将
zip()
替换为
itertools.zip_longest()
map('.join,zip_longest(*[iter(s)]*2,fillvalue='')
也很有用:这是一个非常好的答案,因为它不会以任何方式令人费解,这一事实使您能够轻松记住该方法,因为它具有simplicity@TrevorRudolph它只会按你说的做。上面的答案实际上只是一个for循环,但用pythonical表示。此外,如果你需要记住一个“过于简单化”的答案,至少有数十万种方法可以记住它们:在stackoverflow页面上加星号;复制然后粘贴到电子邮件中;保存一个“有用”的文件,里面有你想记住的东西;只要在需要的时候使用现代搜索引擎;在(可能)每个网络浏览器中使用书签;等等,但在第二个问题上,你似乎是认真的。我真的希望你是认真的,因为它真的不复杂。我是认真的,我在模拟器的二进制转换器中使用了这段代码,我喜欢它是pythonic for loop haaha,但感谢你进一步解释为什么我喜欢这个方法!讽刺的是