Removing Leading Numbers From a Field

3296
22
04-28-2022 06:50 AM
jfkuhn
by
New Contributor

I have a tracts field (Tract) which I want to strip off the first 4 numbers in an attribute table.  I created a new field (Tract2) for it.  I've tried several commands without success using the field calculator.  I'm receiving errors 

0 Kudos
22 Replies
jcarlson
MVP Esteemed Contributor

What have you tried so far? And what errors do you get? What kind of field is it, string or numeric?

Assuming a string, you could try either of these approaches.

Arcade:

Right($feature.Tract, Count($feature.Tract) - 4)

Python:

 !Tract![4:]

 

Edit: Tweaked the Python bit. Thanks, Curt! Also, could @jfkuhn please elaborate on the intended output here? Do you want the first four characters to end up in the new field, or do you want the remaining characters after the first 4 are removed?

- Josh Carlson
Kendall County GIS
0 Kudos
curtvprice
MVP Esteemed Contributor

Census tract codes are text fields, so your syntax would work.

However, your code gets the last four numbers. To get the first 4 numbers you can use the Left function, or in python use the slice expression [:4].

0 Kudos
jcarlson
MVP Esteemed Contributor

D'oh! Thank you for catching that. Although, thinking about it more, it's not totally clear if "strip off" means that the first 4 numbers are being removed from the output, or if it's the first 4 that they want to keep. I guess [4:] would be the other way.

- Josh Carlson
Kendall County GIS
jfkuhn
by
New Contributor

1st 4 number will be removed

0 Kudos
jfkuhn
by
New Contributor
 
0 Kudos
curtvprice
MVP Esteemed Contributor

I think this could be done in Arcade, but Python is MUCH easier for this task, use @jcarlson suggestion:

Tract[4:]

 

jfkuhn
by
New Contributor

For some reason what was suggested didn't work.  See my screen capture

0 Kudos
jcarlson
MVP Esteemed Contributor

Ah, that usually happens if there's a null value in the sample row the tool uses to validate your expression. We need to be sure we handle null values in our expression.

Also, Left(string, x) returns the left-most x characters, so it's going to preserve the left characters, rather than remove them.

Try this:

var t = $feature['Tract']

if (IsEmpty(t)){
    return ''
} else {
    return Right(t, Count(t)-4)
}

 

- Josh Carlson
Kendall County GIS
0 Kudos
curtvprice
MVP Esteemed Contributor

I hate that "circus language" with a white heat, but then I'm a desktop person (no JavaScript for me) and I'm old and hate being forced to learn yet another thing.

Python example:

 

# expression
f(!Tract!)
# code block
def f(tract):
    try:
        return tract[4:]
    except:
        pass

 

 

0 Kudos