# Field calculator to copy numeric values from other fields

FieldA contains text: both numeric(123) and alpha-numeric(123a, 2-3, 3/2, '). FieldB is longstring. I want to use field calculator and codeblock on FieldB to bring from Field A only the numeric values.

while True:

``````try:
val = int(x)
print (val)
break
except ValueError:
print ("non-numeric")
break
``````

I tried something similar to the code seen here, but the process fails at some point. I just need something to see if fieldA .isdigit and if true copy to fieldB(if false pass a string "non-numeric"). Or anything similar.

I am using ArcGIS 10.2 for Desktop.

• Have you tried the arcpy.da.SearchCursor option? and later arcpy.updateCursor in a if-else, if true update the cursor, if its false dont update... Jan 22 '15 at 13:00

Have a look at this bit of code as your fieldB is of type string it does not need to do any type conversion.

This bit of python goes in the code block:

``````def numonly(s):
if s.isdigit():
return s
else:
return ""
``````
• it works: I've also combined it with len(s) < 6 because some numbers will be bigger than the longinteger max number. But, values like "023", "050" will be returned without the first "0" Jan 22 '15 at 14:26
• i will answer my own question: FieldB allows long integer, but it will round the values. If i run the code in FieldC(text field), the value will be imported as is (e.g. "006") Jan 22 '15 at 15:01
• Numeric fields never store leading zeros, so if they are important, say they are an ID of some sort, then you have to write them into a string field to retain the leading zeros. Jan 22 '15 at 15:19

Open Field Calculator on FieldB. On Field Calculator, check Show Codeblock.

Paste this code under Pre-Logic Script Code:

``````# assuming FieldB is Long Integer as you mentioned "FieldB is longstring".
# there is no such data type. I'm taking "longstring" as typo error for Long Integer

def get_numbers(value):
return value if str(value).strip().isdigit() else None
``````

``````# assuming FieldB is Text (String) as you mentioned "FieldB is longstring".
# there is no such data type. I'm taking "longstring" as typo error for Long Integer

def get_numbers(value):
return value if str(value).strip().isdigit() else None
``````

and call this function for FieldB.

``````FieldB=
get_numbers(!FieldA!)
``````

I hope this will help. :)