I am trying to port this code to python 3 and am having a terrible time trying to recreate this expression. I am really new to python but more specifically these expressions. the varible dateStart and dateEnd are int as well as Num in the table being a LONG
expression = "mid(trim(str([Num])), 5, 4) not between '" + dateStart + "' and '" + dateEnd + "'"
arcpy.management.SelectLayerByAttribute("workLyr", "NEW_SELECTION", expression)
So mid(string, 5, 4) meaning give me the substring beginning at character 5 and 4 chars long, right?
In python it would be:
str(!FieldName!)[5:8]
or.. give me a string starting at position 5 and ending at position 8
so it returns characters at positions 5,6,7,8
That may help with part of it, but I am not sure I am formatting the entire expression correctly as I keep getting invalid expression error. The quotes and single quotes are really confusing.
Python slicing is start to stop, not start through stop, so [5:8] returns only 3 characters and not 4 characters.
Is the expression variable correct? You set the expression with the variable named "expression1" but the function is taking a variable named "expression"
yes sorry that was a copy and paste error as it appears a couple of times in the code but it matches in the code.
So, I have changed it to this and still get an invalid expression error.
expression = "str(!Num!)[4:7] not between '" + dateStart + "' and '" + dateEnd + "'"
arcpy.management.SelectLayerByAttribute("workLyr", "NEW_SELECTION", expression)
When I try just building your expression I get an error before I even get to the arcpy tool: (The specific values I used don't matter for test building expression, just the data types matter, and I had to change !Num! to just Num for testing)
>>> Num = 123456
>>> dateStart = 1
>>> dateEnd = 2
>>> expression = "str(Num)[4:7] not between '" + dateStart + "' and '" + dateEnd + "'"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>>
Are you sure you are pasting your exact code?
This was the original code.
expression = "mid(trim(str([Num])), 5, 4) not between '" + dateStart + "' and '" + dateEnd + "'"
arcpy.management.SelectLayerByAttribute("workLyr", "NEW_SELECTION", expression)
If you are using ArcGIS Pro, I suggest you use literal strings or f-strings:
expression = f"{str(Num)[4:7]} not between {dateStart} and {dateEnd}"