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!
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!)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With