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)
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.
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)
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().
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)
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:
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)
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)
这些函数具有内存效率,适用于任何迭代.
我被困在同一个场景中。
这对我有用
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)
试试下面的代码:
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']
>>> 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)
一如既往,对于那些喜欢单衬的人
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)
试试这个:
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)