Search code examples
pythonodooodoo-8odoo-9

Split vals depending on condition


I need to split invoice.number like if there is white-space Serial is first part and Number is second. But also if there is no whitespace then Serial stays blank and Number will be all invoice.number. how can i do it? i need to create some IF statement in my for loop ?

Update

for Exmaple invoice.number is AA 555 so Serial will be AA and number will be 555 , but if invoice.number is AA555 Serial will be "" and Number will be AA555. But we don't know what exact invoice.number will be

for line in invoice.invoice_line_ids:
     vals = {
            'Serial': invoice.number or '',
            'Number':invoice.number or '',
            }

Solution

  • Becase the values is a dictionary, so you can use it very sample,

    def parse(number):
        resultList = []
        resultDirt = dict()
        tempList = number.split(" ")
        if len(tempList) > 1:
            resultDirt['Serial'] = tempList[0]
            resultDirt['Number'] = tempList[1]
        else:
            resultDirt['Serial'] = ""
            resultDirt['Number'] = tempList[0]
    
        resultList.append(resultDirt)
        print(resultList)
        return resultList
    
    parse("1321321 jkhhkhk")
    parse("13215465465")
    

    The output is,

    [{'Number': 'jkhhkhk', 'Serial': '1321321'}]
    [{'Number': '13215465465', 'Serial': ''}]