Add trailing zeros to field

1632
6
Jump to solution
02-01-2017 09:21 AM
CCWeedcontrol
Occasional Contributor III

I have a table BuildingTable with building info. There is a field called "Build_num" with characters like B37828 or B2898101 or R29499010C or R29499010C2 that i need to join to a shapefile but the the Shapefile BuildNum has a max of 11 characters like so B3782800000 or B2898101000. so i can't join the table to shapefile.

How can update the BuildingTable field "Build_num" to add trailing zeros to that field?

I tried the following, i added a new filed to insert the new Build numbers with the trailing zeros but nothing happened.

import arcpy

fc = "BluidingPermitsTable"
fields = ('Build_num', 'BuildNum')
with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        if row[0] <= 11:
            row[1] = '0' + str(row[0])
            cursor.updateRow(row)

Thanks.

0 Kudos
1 Solution

Accepted Solutions
RandyBurton
MVP Alum

To add trailing zeros, try something like:

BuildNum = "B37828"
print BuildNum.ljust(11,'0')

print "B2898101".ljust(11,'0')

# for your code
row[1] = row[0].ljust(11,'0')
‍‍‍‍

View solution in original post

6 Replies
RandyBurton
MVP Alum

To add trailing zeros, try something like:

BuildNum = "B37828"
print BuildNum.ljust(11,'0')

print "B2898101".ljust(11,'0')

# for your code
row[1] = row[0].ljust(11,'0')
‍‍‍‍
DanPatterson_Retired
MVP Emeritus

Or for current and future versions of python.

"{!s:0<11}".format(BuildNum)
'B3782800000'
RandyBurton
MVP Alum

Knew there had to be a way using .format.  Thanks Dan_Patterson

0 Kudos
DanPatterson_Retired
MVP Emeritus

It is being replaced with....  f"stuff formating{}" ... to simplify having to do "stuff formatting {}".format.  It is now in la familigia with s", r" and a" formatting.  Came out in python 3.6.  ArcMap-athians aren't going to see it for a while and Pro is still on 3.4

FYI Overview — Python 3.6.0 documentation  and 3.7 Dev is there for sneak preview for those that want to pre-book

BlakeTerhune
MVP Regular Contributor
ArcMap-athians

CCWeedcontrol
Occasional Contributor III

Thanks to both of you, both options worked great.

0 Kudos