Merging Strings for a new key

302
4
Jump to solution
01-07-2022 04:36 PM
DEWright_CA
Occasional Contributor III

So I am updating a working in 10.8.1; before we migrate to Pro. I have a couple existing values (quarter and year_2dig) that we use. I an wanting to do something like this:

valuePrefix = "Q" + str(quarter) + str(year_2dig) + "_"
 
Then 
 
arcpy.CalculateField_management(loccode_fc, "QRTR_KEY", '"valuePrefix !OBJECTID!"', "PYTHON","")
 
So I would have a new unique value that says Q122_1 ... etc for each row
 
But instead I get "colPrefix + 1" as the value...  Ideas?
Tags (3)
0 Kudos
1 Solution

Accepted Solutions
JohannesLindner
MVP Regular Contributor
valuePrefix = "Q" + str(1) + str(22) + "_"
'"' + valuePrefix + "!OBJECTID!" + '"'
# '"Q122_!OBJECTID!"'

That doesn't seem right.

'"' + valuePrefix + '"' + " + str(!OBJECTID!)"
# '"Q122_" + str(!OBJECTID!)'

Have a great day!
Johannes

View solution in original post

4 Replies
DuncanHornby
MVP Frequent Contributor

It looks like you are erroneously embedding your string within the string and using the wrong python parser,

Your code should be:

valuePrefix = "Q" + str(quarter) + str(year_2dig) + "_"
arcpy.CalculateField_management(loccode_fc, "QRTR_KEY", '"' + valuePrefix + "!OBJECTID!" + '"',"PYTHON_9.3","")

 

 

JohannesLindner
MVP Regular Contributor
valuePrefix = "Q" + str(1) + str(22) + "_"
'"' + valuePrefix + "!OBJECTID!" + '"'
# '"Q122_!OBJECTID!"'

That doesn't seem right.

'"' + valuePrefix + '"' + " + str(!OBJECTID!)"
# '"Q122_" + str(!OBJECTID!)'

Have a great day!
Johannes
DEWright_CA
Occasional Contributor III

Perfect; so I was close; I thought it was just a mixture of the right set of quotes and double-quotes just was running out of places to try.

0 Kudos
JohannesLindner
MVP Regular Contributor
# CalculateField can be a little hard to understand, because you have to pass
# a string that evaluates to a correct Python expression. Biggest pitfall that
# I see on this forum is concatenating strings, because people get mixed up
# with the quotation marks of their expression and the quotation marks _around_
# the expression (that make it into a string).

# It's not clear from your question where quarter and year_2dig come from,
# chose the correct expression from below. Alo, note the double quotes inside
# the expression and the single quotes to turn the expression into a string.

# if quarter and year_2dig are fields in the table, this will result in
# '"Q{}{}_{}".format(!QUARTER!, !YEAR_2DIG!, !OBJECTID!)'
expression = '"Q{}{}_{}".format(!QUARTER!, !YEAR_2DIG!, !OBJECTID!)'

# if quarter and year_2dig are python variables, this will result in
# '"Q122_{}".format(!OBJECTID!)'
expression = '"Q{}{}_'.format(quarter, year_2dig) + '{}".format(!OBJECTID!)'

arcpy.CalculateField_management(loccode_fc, "QRTR_KEY", expression, "PYTHON_9.3", "")

 


Have a great day!
Johannes