Python how to handle split when delimiter not present?
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
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!)
>>> buildfile, _, target = "hello#world".partition("#")
>>> buildfile, target
('hello', 'world')
>>> buildfile, _, target = "hello".partition("#")
>>> buildfile, target
('hello', '')
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]))