Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to handle split when delimiter not present?

Tags:

python

syntax

I have the following python code:

def split_arg(argv):
    buildDescriptor = argv[1]
    buildfile, target = buildDescriptor.split("#")

    return buildfile, target

It expects a string (argv[1]) of the form buildfile#target and splits them into two variables of the same name. So a string like "my-buildfile#some-target" will get broken into my-buildfile and some-target respectively.

Sometimes though, there won't be "#" and target; sometimes you'll just have "my-buildfile", in which case I just want target to be "" (empty).

How do I modify this function so that it will handle instances where "#" doesn't exist and it returns buildfile with an empty target?

Currently, if I pass just the buildfile, it throws an error:

buildfile, target = buildDescriptor.split("#")
ValueError: need more than 1 value to unpack

Thanks in advance!

like image 679
IAmYourFaja Avatar asked Oct 14 '12 22:10

IAmYourFaja


2 Answers

I'd use the obvious approach:

    buildfile, target = buildDescriptor.split("#") if \
                        "#" in buildDescriptor else \
                        (buildDescriptor, "")

Note that this will also throw an Exception when there is more than one "#" in buildDescriptor (which is generally a GOOD thing!)

like image 188
ch3ka Avatar answered Oct 22 '22 03:10

ch3ka


First, put the result of the split in a list:

split_build_descriptor = buildDescriptor.split("#")

Then check how many elements it has:

if len(split_build_descriptor) == 1:
    buildfile = split_build_descriptor[0]
    target = ''
elif len(split_build_descriptor) == 2:
    buildfile, target = split_build_descriptor
else:
    pass  # handle error; there's two #s
like image 34
icktoofay Avatar answered Oct 22 '22 05:10

icktoofay