Select to view content in your preferred language

# Adding zeros or numbers in a Field

5385
26
10-24-2014 01:32 PM
Occasional Contributor III

I have two fields that I need to concatenate together but I need to add zeros so one said has 4 digits and the other side has 2 digits. Both separated with a hypen. For Example, 0024-14.

This is the code I have written am I close???

Left([ACONTROL], 4, "-") & Right([ASECTION], 2)

So, it would be field ACONTROL with 4 digits and ASECTION with 2 digits.

1 Solution

Accepted Solutions
MVP Emeritus

OMG  you might be using an older version of Arcmap and not Python 2.7 or above

try this

"00{0}-0{1}".format(int(!ACONTROL!)),int(!ASECTION!))

grief...if that is it...note to both of ourselves...arcmap and python version are needed

26 Replies
MVP Emeritus

In python

```>>> for ACONTROL in [1,10,24]:
...  for ASECTION in [2,10,20]:
...   print"00{}-0{}".format(ACONTROL,ASECTION)
...
001-02
001-010
001-020
0010-02
0010-010
0010-020
0024-02
0024-010
0024-020
>>>
```

or do you want the first condition to read 0001-02 (line 5) and the one on line 11 to  read 0024-002?

Occasional Contributor III

I can write this code in Field calculator right??

MVP Emeritus

for this specific case use

print"00{}-0{}".format(!ACONTROL!,!ASECTION!)

using the python parser

as I indicated there are other options depending on all your possible conditions

Regular Contributor

I think zfill would be a little more flexible:

print "%s-%s" % (!ACONTROL!.zfill(4), !ASECTION!.zfill(2))

That will automatically pad the input with the correct number of zeros.

Occasional Contributor III

I'm thinking I have to have it as a shapefile because I keep getting errors for the code. It keeps saying invalid syntax. I'm typing them as is. Do I have to put something in front of print??

I am typing in field calculator box

print"00{}-0{}".format(ACONTROL,ASECTION)

MVP Emeritus

"00{}-0{}".format(!ACONTROL!,!ASECTION!)

this assumes that you are using the python parser in the field calculator and you have two fields named as above, capitalized etc and in python fields are enclosed in ! ! 's

Occasional Contributor III

Typing it exactly like you have it. I am getting a ValueError : zero length field name in format. I have those field names so I'm not sure why it doesn't like it.

MVP Emeritus

you added a text field...correct...and are doing the calculation there.  a screen grab of your table with the field calculator would go a long way to shortening this thread

Occasional Contributor III

Yes! I just looked to double check. I'll attach 2 screen shots. One of the table one of the field calculator. Let me know if you need anything else. I am going to keep trying to figure it out.