Select to view content in your preferred language

Format numbers in Field Calc/Python

2910
4
10-13-2015 09:02 AM
GeorgePapamihalakis
Regular Contributor

Hi, I am new to python and I am trying to format numbers and concatenate them using python. I basically want to pad numbers with 0s. For example, 5236 should be formatted as 05236 or if it was 300, it should be 00300. I have 4 fields that I want to concatenate.

SSN - no formatting

Block - 5 characters

Lot - 4 characters

Qual - 5 characters

Here is what I have so far, Im not sure why my formatting is not working.

!SSN! + '-' + !BLOCK!.format(00000) + '-' + !LOT!.format(0000) + '-' + !QUAL!.format(00000)

0 Kudos
4 Replies
DanPatterson_Retired
MVP Emeritus

A tip

>>> frmt = "{}-{:0>5}-{:0>4}-{:0>5}".format("abcd",123,456,7890)
>>> print(frmt)
abcd-00123-0456-07890
>>>

As you see fit...

read the docs  Python mini format language​  applies to python 2.7 and 3.4 etc

Learn more....

https://community.esri.com/blogs/dan_patterson/2015/10/13/before-i-forget-17-formatting-in-action

IanMurray
Honored Contributor

I'm not good with the .format string function, but the .zfill string function should do what you need

from 7.1. string — Common string operations — Python 2.7.10 documentation

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

string.zfill(s, width)

Pad a numeric string s on the left with zero digits until the given width is reached.  Strings starting with a sign are handled correctly.

DarrenWiens2
MVP Alum

This is specifically handled by zfill():

>>> block = 5236
... print str(block).zfill(5)
...
05236
GeorgePapamihalakis
Regular Contributor

Awesome! Thanks for the quick responses everyone, I used the zfill function.

Thanks!

0 Kudos