Select to view content in your preferred language

How do you add dashes using field calculator? Example 6411 10 6411 12 to 6411-10 6411-12

5835
6
07-08-2016 02:10 PM
MikeLetterman
Deactivated User

I have a feature in a geodatabase with over a thousand records and need to add dashes to the numbers in a field.

Example: 6411 10 6411 12 to 6411-10 6411-12

0 Kudos
6 Replies
ChrisDonohue__GISP
MVP Alum

For starters, you would need a field that is a string type (text) not numerical.  You can then populate it by concatenating a dash into it at the appropriate places.

For example, a simplistic way would be to shred 6411 10 6411 12 down to it's 4 pieces and place each piece in it's own field, say field A, B, C, D.  For example, A would contain 6411, B 10, etc.  Then create a text field for your final result, we'll call it field E.  Then run Field Calculator ​on field E, with the VB script expression:  & "-" & & " " & & "-" & .

There are probably even easier/more elegant ways to do this with Python.

One catch will be whether all your data is laid out in the same sequence; if it varies it may take some data cleanup or additional code to get it sorted out before concatenating.

Chris Donohue, GISP

DanPatterson_Retired
MVP Emeritus

In python it is a bit easier since there is a way to do away with all that stupid converting types from int/float to string and the like. onsider

>>> a = 1
>>> b= 'b'
>>> c=1.2
>>> d ='x'
>>> "{}-{}-{}-{}".format(a,b,c,d)
'1-b-1.2-x'

now your destination field still needs to be a string, but all you need to do is set your parser to python and use your field names enclosed in exclamation marks  like

"{}-{}-{}-{}".format( !a!, !b!, !c!, !d! )

BlakeTerhune
MVP Regular Contributor

I like the string.format() method because the values your concatenating with the dashes don't have to be strings, it will do the casting automatically. But like Dan mentioned, just make sure the output field is a string with a long enough length to accommodate the new value.

DanPatterson_Retired
MVP Emeritus

in python 3.6, this is now even more simplified...

if you like raw format r"f:\test\path"

you will love the new format  What’s New In Python 3.6 — Python 3.6.0a2 documentation

f formatting

>>> name = "Fred"

>>> f"He said his name is {name}."

'He said his name is Fred.'

BlakeTerhune
MVP Regular Contributor

Oooh, shiny.

JoshuaBixby
MVP Esteemed Contributor

I agree, formatted string literals are nice syntactic sugar.  Unfortunately, we still have some time until final release and then a bit longer until incorporated into ArcGIS products.

0 Kudos