Following along with your example's logic, this jumped out as the most expedient method of finding the "first" matching arrow and printing it's location. However, the order of sets are not FIFO, so if you want to preserve order I would suggest substituting a list instead of a set for arrowlist so that the order can be preserved.
arrowlist = {"->x","->", "->>", "-\\", "\\-","//--","->o","o\\--","<->","<->o"}
def cxn(line, arrowlist):
try:
result = tuple((x, line.find(x)) for x in arrowlist if x in line)[0]
print("found an arrow {} at position {} with length {}".format(result[0], result[1], len(result[0])))
# Remember in general it's not a great idea to use an exception as
# broad as Exception, this is just for example purposes.
except Exception:
return 0
If you're looking for the first match in the provided string (line), you can do that like this:
arrowlist = {"->x","->", "->>", "-\\", "\\-","//--","->o","o\\--","<->","<->o"}
def cxn(line, arrowlist):
try:
# key first sorts on the position in string then shortest length
# to account for multiple arrow matches (i.e. -> and ->x)
result = sorted([(x, line.find(x)) for x in arrowlist if x in line], key=lambda r: (r[1],len(r[0])))[0]
# if you would like to match the "most complete" (i.e. longest-length) word first use:
# result = sorted([(x, line.find(x)) for x in arrowlist if x in line], key=lambda r: (r[1], -len(r[0])))[0]
print("found an arrow {} at position {} with length {}".format(result[0], result[1], len(result[0])))
except Exception:
return 0
Or, if you have access to the standard library you can use operator.itemgetter to almost the same effect and gain efficiency from less function calls:
from operator import itemgetter
arrowlist = {"->x","->", "->>", "-\\", "\\-","//--","->o","o\\--","<->","<->o"}
def cxn(line, arrowlist):
try:
# key first sorts on the position in string then alphanumerically
# on the arrow match (i.e. -> and ->x matched in same position
# will return -> because when sorted alphanumerically it is first)
result = sorted([(x, line.find(x)) for x in arrowlist if x in line], key=(itemgetter(1,0)))[0]
print("found an arrow {} at position {} with length {}".format(result[0], result[1], len(result[0])))
except Exception:
return 0
***NOTE: I am using a slightly different arrowlist than your example just because the one you provided seems to be messing with the default code formatting (likely because of quote closure issues). Remember you can prepend a string with 'r' like this: r"Text that can use special symbols like the escape \and\ be read in as a 'raw' string literal\"
. See this question for more information about raw string literals.