Skip to content

Instantly share code, notes, and snippets.

@wallabra
Created March 28, 2016 00:19
Show Gist options
  • Select an option

  • Save wallabra/d3bab7ac8696433b6a9a to your computer and use it in GitHub Desktop.

Select an option

Save wallabra/d3bab7ac8696433b6a9a to your computer and use it in GitHub Desktop.
A simple function that splits a string IF and ONLY IF the condition returned by the call to the first argument is True.
from argparse import ArgumentError
def conditional_split(split_function, input_string, separator=None):
# splits the string into a list
result = input_string.split(separator)
# makes the check in each item of the list
for x in xrange(len(result) - 1):
try:
# checks if the function returns True for both sides of the split
if not split_function(result[x], result[x + 1]):
# If not, undo the split by popping the two sides of the split
# and inserting a merged string in the location instead.
part_a = result.pop(x)
part_b = result.pop(x + 1)
print "{0} + {1} = \"{0} {1}\"".format(part_a, part_b)
result.insert(x, "{0} {1}".format(part_a, part_b))
else:
# If yes, then print for debugging reasons!
print "{0} | {1}".format(result[x], result[x + 1])
# stops whenever a IndexError is hit. tries to preserve the result acquired
except IndexError:
print "Index {0} is {1}.".format(x - 1, result[x - 1])
break
# makes sure the function argument has a correct number of arguments
except ArgumentError:
raise ValueError(repr(split_function) + " has a invalid number of arguments!")
return result
# splits only if in both sides of the split, one of the words separed by "," are also one
# of the words in the other side separed by ",".
my_func = (lambda x, y: True in (z in y.split(",") for z in x.split(",")))
# the input string
my_string = u"abdicate,much abdicate,awesome so,much so,cool so,hello idk,guys,so,cool why,so,then,awesome"
# prints are good! :)
print my_string
# do it! do it!
my_result = conditional_split(my_func, my_string, " ")
# prints out thy result
print "{0} from {1}".format("|".join(my_result), my_result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment