-2

How could I split a string before any character and after any character. E.g:

x = '846a12'

How would I output:

z = ['846','a','12']

The problem in this case is I have mentioned specific character in my function (specific character: 'a' in above example). If input is different character(Let's say: 'b') my function fails. How can I deal with random characters?

Thanks.

Sayali Sonawane
  • 12,289
  • 5
  • 46
  • 47
Lucas
  • 25
  • 3

1 Answers1

0

You can use itertools for solving these types of problems, for the cases where there are more than one occurrence of the separator, e.g.:

>>> import itertools as it
>>> [''.join(x) for _, x in it.groupby('846a12', key=lambda c: c=='a')]
['846', 'a', '12']
AChampion
  • 29,683
  • 4
  • 59
  • 75
  • Really? This is a terrible solution compared to either of the other two solutions in the comments. It's much less readable, and I would be willing to bet it's less efficient as well. – Morgan Thrapp Sep 06 '16 at 15:09
  • Agree, if there is only one occurrence of the separator, and I'm not sure it is that terrible compared to the `re` based solutions. – AChampion Sep 06 '16 at 15:10
  • Nope, the linked dupe takes care of multiple occurrences of the separator. – Morgan Thrapp Sep 06 '16 at 15:11