Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading