Search code examples
pythonstringif-statementstring-formatting

Create a list of strings from a string having '+' character. Using '+' to separate the lists


I have a sample input string as follows:

med_str = 'Film-coated tablet + ALpha Chloro, Prolonged-release tablet + ALFU Dioxide'

I want to create a list of strings separated by '+'. OUTPUT expected:

med_str = ['Film-coated tablet', 'ALpha Chloro'], ['Prolonged-release tablet', 'ALFU Dioxide']

There might be cases where there would be only one '+' separated string. Example:

new_str = 'Tablet + DEFLAZo'

OUTPUT expected:

new_str = ['Tablet', 'DEFLAZo']

How do I do this using an if else in python which should take care of all the cases and create a separate list of strings separated by comma whenever there is/isn't one or more than one elements with '+' in the string and separated by comma.


Solution

  • Assuming your string always has a whole number of paris, here's how it could be done:

    med_str = 'Film-coated tablet + ALpha Chloro, Prolonged-release tablet + ALFU Dioxide'
    
    cleaned = [s.strip() for s in med_str.replace('+',',').split(',')]
    result = [[cleaned[i], cleaned[i+1]] for i in range(0, len(cleaned), 2)]
    print(result)
    

    Output:

    [['Film-coated tablet', 'ALpha Chloro'], ['Prolonged-release tablet', 'ALFU Dioxide']]