How to convert single number into 3 digit code using Python and field calculator?

03-29-2018 11:21 AM
New Contributor

I have three fields in an attribute table that I have combined through the field calculator to generate one value in my 'name field'. It displays like this - 'RSB01-1'. However, I want the final digit to display as a three digit code e.g 001 instead of just 1. What python function do I use in the field calculator?

The code I have looks like this : ''.join([ !NRS!, !NSA!, "-", str(!SeqNo!)] )

I know some function is needed around the final field (str(!SeqNo!), I jut don't know what.

Tags (3)
0 Kudos
4 Replies
MVP Regular Contributor

If you put something like this into the 'Pre-Logic Script Code' of the Field Calculator tool, it may work. 

def calc(field1, field2, field3):
     if len(str(field3)) == 1:
          return ("{0}{1}-00{2}".format(field1,field2,field3))
     if len(str(field3)) == 2:
          return ("{0}{1}-0{2}".format(field1,field2,field3))
     if len(str(field3)) == 3:
          return ("{0}{1}-{2}".format(field1,field2,field3))

0 Kudos
MVP Esteemed Contributor

There are plenty of ways to go about this task.  You could just change your existing code to:

''.join([!NRS!, !NSA!, "-", ("00" + str(!SeqNo!))[-3:]])
MVP Legendary Contributor

Python parser, with pre-padding as a field calculator expression. Just replace 'a', 'b', 'c' with your field names in ! 


a = 'first_'

b = 'second'

c = 1

"{}{}-{:>03.0f}".format(a, b, c)

c = 10

"{}{}-{:>03.0f}".format(a, b, c)

# --- for fields a, b, c, just use python parser !YourFirstField!, etc
MVP Regular Contributor

String formatting is good but I always forget the more complex format codes and have to look it up and experiment every time. Might be simpler to use the zfill function: 


    "{}{}-{}".format(!NRS!, !NSA!, str(!SeqNo!).zfill(3))