本文翻译自:Split string every nth character?
Is it possible to split a string every nth character? 是否可以每n个字符分割一个字符串?
For example, suppose I have a string containing the following: 例如,假设我有一个包含以下内容的字符串:
'1234567890'
How can I get it to look like this: 我怎样才能使它看起来像这样:
['12','34','56','78','90']
#1楼
参考:https://stackoom.com/question/dkwT/每n个字符分割一个字符串
#2楼
I like this solution: 我喜欢这个解决方案:
s = '1234567890'
o = []
while s:
o.append(s[:2])
s = s[2:]
#3楼
You could use the grouper()
recipe from itertools
: 您可以使用itertools
grouper()
配方:
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)
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)
These functions are memory-efficient and work with any iterables. 这些函数可节省内存,并且可与任何迭代程序一起使用。
#4楼
As always, for those who love one liners 一如既往,对于那些喜欢一只班轮的人
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])]
#5楼
Spooky one – tried to invent yet another answer: 诡异的-尝试发明另一个答案:
def split(s, chunk_size):
a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
return [''.join(t) for t in a]
print(split('1234567890', 1))
print(split('1234567890', 2))
print(split('1234567890', 3))
Out 出
['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
['12', '34', '56', '78', '90']
['123', '456', '789']
#6楼
I've got this code that I use whenever I need to do this: 每当执行此操作时,我都会使用以下代码:
def split_string(n, st):
lst = [""]
for i in str(st):
l = len(lst) - 1
if len(lst[l]) < n:
lst[l] += i
else:
lst += [i]
return lst
print(split_string(3, "test_string."))
Where: 哪里:
-
n
is the length of each list itemn
是每个列表项的长度 -
st
is the string to be split upst
是要拆分的字符串 -
lst
is the list version ofst
lst
是st
的列表版本 -
i
is the current character being used inst
i
是st
中使用的当前字符 -
l
is the length of the last list iteml
是最后一个列表项的长度