0

I have a string such as '01301347' and I want to split it into something like '01-13-30-01-13-34-47'.

Is it possible to do something like this using split()?

ovgolovin
  • 13,063
  • 6
  • 47
  • 78
user415663
  • 735
  • 2
  • 7
  • 9
  • look here: http://stackoverflow.com/questions/9475241/split-python-string-every-nth-character?rq=1 – astrognocci Jul 15 '13 at 20:22
  • Split should be used for finding letters or numbers, and it is an inefficient process so try not to use it when you can do something else. – debianplebian Jul 15 '13 at 20:25

3 Answers3

3

You want to splice and join, not split:

'-'.join(mystr[i:i+2] for i in xrange(0, len(mystr)-1))

You could also use itertools.islice and itertools.izip:

'-'.join((a+b for a,b in itertools.izip(mystr, itertools.islice(mystr, 1, len(mystr)))))
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1
>>> s = '01301347'
>>> '-'.join(s[i:i+2] for i in range(0, len(s) - 1))
'01-13-30-01-13-34-47'

or you can use:

>>> '-'.join(a+b for a,b in zip(s, s[1:]))
'01-13-30-01-13-34-47'
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0
>>> from operator import add
>>> from itertools import starmap
>>> '-'.join(starmap(add,zip(*[iter(s)]*2)))
'01-30-13-47'

Explanation:

>>> zip(*[iter(s)]*2)
[('0', '1'), ('3', '0'), ('1', '3'), ('4', '7')]

add is equivalent for +: a + b = add(a,b)

starmap applies function to unpacked list of arguments from each value from iterable.

>>> list(starmap(add,zip(*[iter(s)]*2)))
['01', '30', '13', '47']

Lastly we just join them:

>>> '-'.join(starmap(add,zip(*[iter(s)]*2)))
'01-30-13-47'

By the way, we can avoid having to use starmap and add by writing it in a bit different way:

>>> '-'.join(map(''.join,zip(*[iter(s)]*2)))
'01-30-13-47'
ovgolovin
  • 13,063
  • 6
  • 47
  • 78