Hello!
I am trying to add a hyperlink field to a feature class so I can use it in a pop-up on a viewer. The issue I am having is with the url itself; I receive an invalid syntax error on the url.
The feature class has a 'LINK ID' field, which is a number that sits at the end of a base url. So what I need to do is add a field for the hyperlink (I got that to work just fine), and then calculate this field by concatenating the base url string with the Link ID field. Here is the line of the code that is failing:
arcpy.management.CalculateField(fc, 'HYPERLINK', 'https://msc.fema.gov/portal/downloadProduct?productID='+'LINKID ', "Python 3")
I have tried using .format methods as well, and continue to receive invalid syntax on the url. Any help is appreciated, thank you!
Solved! Go to Solution.
Using Calculate Field in a Python script is a little tricky.
# this works in a Python console, assuming LINKID is a defined variable
'https://msc.fema.gov/portal/downloadProduct?productID=' + str(LINKID)
# or with newer syntax
f'https://msc.fema.gov/portal/downloadProduct?productID={LINKID}'
# for Calculate field, you have to supply the expression as string
"'https://msc.fema.gov/portal/downloadProduct?productID=' + str(!LINKID!)"
"f'https://msc.fema.gov/portal/downloadProduct?productID={!LINKID!}'"
Looks like you have a space between the D and '.
I take it LINKID is a number... Might try casting to string. str(LINKID) I know you tried format, but sometimes you just need to be explicit.
Thanks for the response! I should have been a bit more clear, the syntax error is in the url itself. It does not like the semicolon after the https.
Yep, the link id is a number that will be added on to then end of the url.
I did a little local test and replicated the issue. Using the ! surrounding the field returned an eol expected error as well. Seeing that you are using this in a standalone script, I'd just use an update cursor:
with arcpy.da.UpdateCursor(fc, ['HYPERLINK', 'LINKID']) as uCur:
for row in uCur:
row[0] = fr'https://msc.fema.gov/portal/downloadProduct?productID={row[1]}'
uCur.updateRow(row)
Thanks Jeff! The simple syntax in Johannes' answer was a quick fix, but I will certainly be keeping the update cursor in my mind for future projects.
LinkID needs to be between exclamation points.
arcpy.management.CalculateField(fc, 'HYPERLINK', '"https://msc.fema.gov/portal/downloadProduct?productID="+!LINKID!', "Python 3")
Using Calculate Field in a Python script is a little tricky.
# this works in a Python console, assuming LINKID is a defined variable
'https://msc.fema.gov/portal/downloadProduct?productID=' + str(LINKID)
# or with newer syntax
f'https://msc.fema.gov/portal/downloadProduct?productID={LINKID}'
# for Calculate field, you have to supply the expression as string
"'https://msc.fema.gov/portal/downloadProduct?productID=' + str(!LINKID!)"
"f'https://msc.fema.gov/portal/downloadProduct?productID={!LINKID!}'"
Thanks Johannes, exactly what I needed!