-2

Does anyone know if it's possible in python to split a string, not necessarily by a space or commas, but just by every other entry in the string? or every 3rd or 4th etc.

For example if I had "12345678" as my string, is there a way to split it into "12", "34", "56", 78"?

  • … and a dozen other questions, most of which have arguments about whether slicing or zipping instances of the same iterator is easier to understand/more likely to be what the OP wanted if he had an uneven-length list/faster/less typing/etc. – abarnert Sep 19 '13 at 20:14
  • Darn - couldn't find that nth character one - and even then didn't think it had an re approach - oh well :) – Jon Clements Sep 19 '13 at 20:16

3 Answers3

0

You can use list comprehension:

>>> x = "123456789"
>>> [x[i : i + 2] for i in range(0, len(x), 2)]
['12', '34', '56', '78', '9']
Sajjan Singh
  • 2,523
  • 2
  • 27
  • 34
0

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']
Henry Keiter
  • 16,863
  • 7
  • 51
  • 80
0

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']
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183