Python how to handle split when delimiter not present?

Question:

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!

Asked By: IAmYourFaja

||

Answers:

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
Answered By: icktoofay

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!)

Answered By: ch3ka
>>> buildfile, _, target = "hello#world".partition("#")
>>> buildfile, target
('hello', 'world')
>>> buildfile, _, target = "hello".partition("#")
>>> buildfile, target
('hello', '')

This uses str.partition:

str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

Answered By: Rusty Rob

You can do this in Python 3:

input_string = 'this is a test'
delimiter = '#'

slots = input_string.split(delimiter)
if slots[0] == input_string:
  print('no %s found' % delimiter)
else:
  print('%s found right after "%s"' % (delimiter, slots[0]))
Answered By: David
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.