当前位置: 动力学知识库 > 问答 > 编程问答 >

How to split a string in Python by 2 or 3, etc

问题描述:

This question already has an answer here:

  • What is the most “pythonic” way to iterate over a list in chunks?

    27 answers

  • Split python string every nth character?

    12 answers

网友答案:

You can use list comprehension:

>>> x = "123456789"
>>> [x[i : i + 2] for i in range(0, len(x), 2)]
['12', '34', '56', '78', '9']
网友答案:

You can use a list comprehension. Iterate over your string and grab every two characters using slicing and the extra options in the range function.

s = "12345678"
print([s[i:i+2] for i in range(0, len(s), 2)]) # >>> ['12', '34', '56', '78']
网友答案:

What you want is the itertools grouper() recipe, which takes any arbitrary iterable and gives you groups of n items from that iterable:

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)

(Note that in 2.x, this is slightly different as zip_longest() is called izip_longest()!)

E.g:

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

You can then rejoin the strings with a simple list comprehension:

>>> ["".join(group) for group in grouper("12345678", 2)]
['12', '34', '56', '78']

If you might have less than a complete set of values, just use fillvalue="":

>>> ["".join(group) for group in grouper("123456789", 2, fillvalue="")]
['12', '34', '56', '78', '9']
分享给朋友:
您可能感兴趣的文章:
随机阅读: