有没有人知道在python中是否可以分割字符串,不一定是空格或逗号,而只是字符串中的每个其他条目?或每隔3或4等。
例如,如果我将“12345678”作为我的字符串,有没有办法将其拆分为“12”,“34”,“56”,78“?
答案 0 :(得分:0)
您可以使用列表理解:
>>> x = "123456789"
>>> [x[i : i + 2] for i in range(0, len(x), 2)]
['12', '34', '56', '78', '9']
答案 1 :(得分:0)
您可以使用列表理解。迭代你的字符串并使用切片和range
函数中的额外选项抓住每两个字符。
s = "12345678"
print([s[i:i+2] for i in range(0, len(s), 2)]) # >>> ['12', '34', '56', '78']
答案 2 :(得分:0)
你想要的是the itertools
grouper()
recipe,它接受任意的迭代,并为你提供来自该可迭代的n
项组:
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)
(请注意in 2.x,由于zip_longest()
被称为izip_longest()
,因此略有不同!)
E.g:
>>> list(grouper("12345678", 2))
[('1', '2'), ('3', '4'), ('5', '6'), ('7', '8')]
然后,您可以使用简单的list comprehension重新加入字符串:
>>> ["".join(group) for group in grouper("12345678", 2)]
['12', '34', '56', '78']
如果您的值不够完整,请使用fillvalue=""
:
>>> ["".join(group) for group in grouper("123456789", 2, fillvalue="")]
['12', '34', '56', '78', '9']