ArcGIS Pro 2.8.4: A python expression fails to perform on “field calculator”,
I couldn’t figure out why the python expression below fails to perform on “field calculator
!A! + "/"+ !B!
This expression is supposed to combine the field A and field B in field C. The first value in the C table when computed is assumed to be 33 / 1
What could be the issue here?
The gdb file is attached
Solved! Go to Solution.
Again, use string formatting
f"{!A!:.0f} / {!B!:.0f}"
"{:.0f} / {:.0f}".format(!A!, !B!)
"%.0f / %.0f" % (!A!, !B!)
The error message is telling you that you can't add a string to a number. The "+" operator is for adding numbers or concatenating strings, not adding or concatenating strings to numbers.
Use string formatting instead:
C = f"{!A!} / {!B!}"
# or
C = "{} / {}".format(!A!, !B!)
# or
C = "%s / %s" % (!A!, !B!)
A and B are floats, "/" is a string.
In Python, addition between float and str isn't defined, so the Field Calculator doesn't know what to do.
You have to convert the floats to strings using one of these methods:
# explicitly cast the floats to strings
str(!A!) + "/" + str(!B!)
# implicitly cast to string with str.format()
"{}/{}".format(!A!, !B!)
# implicitly cast to string with format string
f"{!A!}/{!B!}"
The expression (str(!A!) + "/" + str(!B!)) adds one decimal number for each number.
How to eliminate this decimal number?
Again, use string formatting
f"{!A!:.0f} / {!B!:.0f}"
"{:.0f} / {:.0f}".format(!A!, !B!)
"%.0f / %.0f" % (!A!, !B!)
You are making it harder than it has to be. Just don't wrap your Python division character in a string. For example:
!A! / !B!
@JoshuaBixby then will the result be the division of the two numbers (not what OP wants) instead of a string with the two numbers separated by a forward slash (what the OP wants)?
@Luke_Pinner, I was too quick skimming over the question, thanks for pointing out the real question.
Thank you for the help. It works fine