How would I split a python string and keep the separator, but the separator isn't a separate list item?

I already have a program that mostly works.

def separate(char, text, splitat='after'):
  #will split at the point before/after the character you choose
  #if splitat is anything other than before or after, it will function as the split() method

  split = text.split(char)

  if splitat == 'after':
    split = [_ + str(char) for _ in split]
    split[len(split)-1] = split[len(split)-1].split('e')[0]
  elif splitat == 'before':
    split = [str(char) + _ for _ in split]
    try:
      split[0] = split[0].split('e')[1]
    except: pass
  else: return

  return split

but when I run it as separate('x', 'ashkjadhssdx', '{before or after}'), it returns this:

#splitat: before
['xashkjadhssd', 'x']

#splitat: after
['ashkjadhssdx', 'x']

how do I fix this?

>Solution :

Use if condition to check if the length of a string is greater than 1 or not, and only concatenate when the length is greater than 1.

Leave a Reply