-2

有谁知道在 python 中是否可以拆分字符串,不一定是空格或逗号,而是字符串中的所有其他条目?或每 3 次或 4 次等。

例如,如果我的字符串为“12345678”,有没有办法将其拆分为“12”、“34”、“56”、78”?

4

3 回答 3

0

您可以使用列表理解:

>>> x = "123456789"
>>> [x[i : i + 2] for i in range(0, len(x), 2)]
['12', '34', '56', '78', '9']
于 2013-09-19T20:12:01.640 回答
0

您可以使用列表推导。遍历您的字符串并使用切片和range函数中的额外选项抓取每两个字符。

s = "12345678"
print([s[i:i+2] for i in range(0, len(s), 2)]) # >>> ['12', '34', '56', '78']
于 2013-09-19T20:12:59.713 回答
0

你想要的是recipe itertools grouper()它接受任意的迭代,并为你提供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)

(请注意,在 2.x 中,这与zip_longest()所谓的略有不同izip_longest()!)

例如:

>>> list(grouper("12345678", 2))
[('1', '2'), ('3', '4'), ('5', '6'), ('7', '8')]

然后,您可以使用简单的列表理解重新加入字符串:

>>> ["".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']
于 2013-09-19T20:14:24.890 回答