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

513
4
03-29-2018 11:21 AM
JacksonBrown
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
MitchHolley1
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
JoshuaBixby
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:]])
DanPatterson_Retired
MVP Esteemed Contributor

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

demo

a = 'first_'

b = 'second'

c = 1

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

c = 10

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

# --- for fields a, b, c, just use python parser !YourFirstField!, etc
Luke_Pinner
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: 

    str(!SeqNo!).zfill(3)

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

https://docs.python.org/2/library/string.html