Since you're looking for a string in an array of strings, you might have to loop over each string. For example, this would convert the string to lower-case before making the comparison:
indexes = [index for index, name in enumerate(header) if name.lower() == "templatename"]
if len(indexes) == 1:
index = indexes[0]
# There is at least one header matching "TemplateName"
# and index now points to the first header.
Note that the if
statement considers there might be no header or more than one header matching the given name. For your reassurance, also note that lower()
does not change the case of the original string.
You might also find it more obvious to convert all the strings in the header to lower-case before calling index, which looks more like your original code:
try:
index = [name.lower() for name in header].index("templatename")
except ValueError:
# There is no header matching "TemplateName"
# and you can use `pass` to just ignore the error.
else:
# There is at least one header matching "TemplateName"
# and index now points to the first header.
Note that, like before, lower()
does not change the case of the actual header because it is only done within the context of the loop. In fact, strings in Python are immutable so you can't change them in place.
You might also consider regular expressions. For example, this would search for case insensitve without converting the string to lower-case:
import re
indexes = [index for index, name in enumerate(header) if re.match(name, "TemplateName", re.I)]
Note that if you don't really need the index, then you can remove enumerate
and simplify the loop a little.